Shell tricks - Programming On Unix

Users browsing this thread: 4 Guest(s)
josuah
Long time nixers
when to quote

More interesting question: when are quotes necessary?

At first I quoted everything, and a few days ago I discovered that quotes are not necessary at many places.

Answer: when commands are interpreted, at "for var in >>here<<".

Commands arguments

If the variable a have the content '1 2 3'
Code:
$ printf '%s\n' $a
1
2
3

As you may know, the shell did cut the arguments from the space in the string. Still the convenient/cumbersome balance of the shell.

Code:
$ printf '%s\n' "$a"
1 2 3

Ok.

Variables assignation do not need quoting, though that does not hurt to add quotes every time.

Code:
$ b=$a/*
$ printf '%s\n' "$b"
1 2 3/*
$ b="$a /*"
$ printf '%s\n' "$b"
1 2 3 /*
$ b=$a /*
/bin/sh: /bin: cannot execute - Is a directory

Yes, we need quotes when we insert a space directly in the variable, as the syntax "MANPAGER=ul man test" is to call the man command with the environment variable MANPAGER set to ul.

The case statements do not need quoting neither, so you can safely do:

Code:
$ a='1 2 3'
$ case $a in
\ 1) echo 1 ;;
\ 2) echo 2 ;;
\ *) echo '*' ;;
\ esac
*

The for statements are special: they need quoting if you want a variable to be considered as a single item:

Code:
$ a='1 2 3'
$ for i in "$a"; do printf '%s\n' "$i"; done
1 2 3
$ for i in  $a;  do printf '%s\n' "$i"; done
1
2
3

The if and while statements

The tests do need quoting. The [ and ] after the if: the /bin/[ file is often a symlink to /bin/test

Code:
$ if [ -z "$a" ]; then echo true; else echo false; fi
false
$ if grep "$a" < $HOME/.profile; then echo true; else echo false; fi
false
$ while [ -z "$a" ]; do echo niet; done

Shell redirection

The <, >, >> operators do not need quoting.

Code:
$ a='1 2 3'
$ echo content > $a
$ cat < *
/bin/sh: cannot open *: No such file or directory
$ cat < $a

Parameters expansion

In the ${var#pattern}, ${var##pattern}, ${var%pattern}, ${var%%pattern} syntax, you have pattern that can contain globs or plain text for removing text from var. The pattern is interpreted just like with double quotes ("):

Code:
$ var='1 2 3'
$ pattern='1 2 '
$ printf '%s\n' "${var#$pattern}"
2


Messages In This Thread
Shell tricks - by josuah - 13-11-2017, 05:27 AM
RE: Shell tricks - by josuah - 13-11-2017, 05:39 AM
RE: Shell tricks - by venam - 14-11-2017, 01:53 AM
RE: Shell tricks - by josuah - 23-11-2017, 07:59 AM
RE: Shell tricks - by josuah - 23-11-2017, 08:52 AM
RE: Shell tricks - by josuah - 04-12-2017, 07:43 AM
RE: Shell tricks - by z3bra - 04-12-2017, 08:11 PM
RE: Shell tricks - by josuah - 05-12-2017, 08:07 AM
RE: Shell tricks - by josuah - 05-12-2017, 09:02 AM
RE: Shell tricks - by josuah - 05-12-2017, 09:08 AM
RE: Shell tricks - by josuah - 08-12-2017, 12:25 PM