Uncategorized

The 5 simple bits of sh/bash you should know

Bash is a useful programming language to know enough to get by in because it’s there on most Unix systems, and is super lightweight making it perfect for scripts that do small tasks and launch other programs. Not only that, but as a frequent user of the command line, it’s great for one-liners.

1. Looping:

for ((I=0; I<=10; I++)); do echo $I; done

2. Looping over files:

for F in *.jpg; do file “$F”; done

3. Variable regexps and replacements:

for F in *.jpg; do O=${F/.jpg/.png}; convert “$F” “$O”; done

4. Exists expressions:

if [ -e .git ]; then git status; fi

Note1: uses “then” and “fi” instead of “do” and “done”.

Note2: the space before/after the square brackets is required. This weird requirement is easy to forget.

5. The “$@” special parameter

exec some_other_program -param1 -param2 “$@”

This is only useful in actual bash scripts. It passes the original parameters to your script on to “some_other_program” preserving how they should be quoted in bash (e.g. parameters with spaces in will be passed correctly).

I should note that people are likely to comment that there are other ways (and perhaps better ways) to do each of these things, but I find knowing these 5 things incredibly useful for trivial little tasks on the command line. Maybe you have other little tips/tricks to share?

Standard

One thought on “The 5 simple bits of sh/bash you should know

Leave a comment