cancel
Showing results for 
Search instead for 
Did you mean: 
williamwlk
Flight Engineer Flight Engineer
Flight Engineer
  • 3,367 Views

Sharing (this but not food) is caring (Bash scripting cheatsheet)

Hey Folks,

This is good. A real good cheat sheet for Bash.

https://devhints.io/bash

Cheers.

Will

Labels (5)
Tags (3)
4 Replies
Deanna
Community Manager
Community Manager
  • 3,355 Views

Thank you for sharing @williamwlk! Very valuable resource indeed. 

--
Deanna
0 Kudos
williamwlk
Flight Engineer Flight Engineer
Flight Engineer
  • 3,351 Views

My pleasure @Deanna :) and echo your comment (Very valuable resource indeed.).

Will

0 Kudos
Jeff_Schaller
Flight Engineer
Flight Engineer
  • 3,233 Views

Beware of unquoted variable expansions shown as example on that page. For example,

for i in "${arrayName[@]}"; do
  echo $i
done

Should be:

for i in "${arrayName[@]}"; do
  printf '%s\n' "$i"
done

 To see why, create a file named "file1" somewhere:

    cd /tmp

    touch file1

Then create an array like this (note that array element zero is the string "file*"; no filename expansion yet):

    arrayName=('file*')

And then unsafely  run the sample for loop; you'll get:

    for i in "${arrayName[@]}"; do echo $i; done
    file1 

You "accidentally" ran into filename expansion (globbing) when weren't expecting it.

 

Next, consider using printf instead of echo. Load the array this way:

    arrayName=('-e')

and then run the loop; even with proper quoting, you'll get:

    for i in "${arrayName[@]}"; do echo "$i"; done

    

... with a blank line! Using printf instead gets you the actual data:

    for i in "${arrayName[@]}"; do printf '%s\n' "$i"; done
    -e

oldbenko
Moderator
Moderator
  • 3,214 Views

Hey, @Jeff_Schaller,

Well spotted! I have also noticed some weirdness such as:

  • the entire section on conditionals suggests double square brackets but never explains the difference between "[[" and "[" (both are builtins, but "[" is more portable)
  • the section on getting options should use the getopts builtin, everything else is a poor hack
  • the arrays section should explain shift and unshift, not the options one

And of course, whatever is already in the comments.

A black cat crossing the street signifies that the animal is going somewhere.
[don't forget to kudo a helpful post or mark it as a solution!]
0 Kudos
Join the discussion
You must log in to join this conversation.