cancel
Showing results for 
Search instead for 
Did you mean: 
Flight Engineer williamwlk Flight Engineer
Flight Engineer
  • 530 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
Community Manager
Community Manager
  • 519 Views

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

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

0 Kudos
Reply
Loading...
Flight Engineer williamwlk Flight Engineer
Flight Engineer
  • 515 Views

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

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

Will

0 Kudos
Reply
Loading...
Jeff_Schaller Flight Engineer
Flight Engineer
  • 397 Views

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

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

Reply
Loading...
Moderator
Moderator
  • 378 Views

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

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
Reply
Loading...
Join the discussion
You must log in to join this conversation.