0

In a bash script I had this test. Which worked perfectly.

function copy_to_server {
  if [ $1 -nt limit ]; then

Now I want to allow a third parameter to force. But whatever is the value, the test pass:

function copy_to_server {
  if [ $1 -nt limit ] || [ "$3"="-f" ] || [ "$3"="--force" ]; then

How to test properly my parameter ?

mickro
  • 881
  • 2
  • 11
  • 26

1 Answers1

1

You need to include spaces :

if [ "$1" -nt limit ] || [ "$3" = "-f" ] || [ "$3" = "--force" ]; then

Failing to do that, the shell considers the inside of the test like a single argument, and by specification, with a single argument, a test returns "true" (0) if the argument is not empty.

Also, please note I quoted the $1 in the first test : if an argument is passed that contains whitespace, without quotes word splitting will occur, and the shell will see more than three arguments and fail with a syntax error (or at least not do what you want).

If you do not mind Bash-specific syntax, you could use the [[ ]] type of test, which does not perform word splitting.

if [[ $1 -nt limit ]] || [[ $3 = -f ]] || [[ $3 = --force ]]; then

But then, by that point, you can all put them together in a single test, because this style of test also supports logical operators :

if [[ $1 -nt limit || $3 = -f || $3 = --force ]; then

Please note that the = and != operators in [[ ]] test does globbing, so the right hand side needs to be quoted if the string being tested includes something that could trigger a glob (like *).

Fred
  • 6,590
  • 9
  • 20
  • no real need to add quotes to `$1` : those parameters are not directly accessible by end user. – mickro Mar 02 '17 at 12:00
  • @mickro If you are safe with the assumption that the calling context will never pas a multi-word argument, then it will work ; I tend to favor avoiding that assumption, because code tends to be reused at some point, but that is a matter of preference, so not doing it is not "wrong" in the technical sense. – Fred Mar 02 '17 at 12:06
  • Sure. You have a point. – mickro Mar 02 '17 at 12:11