birdemic
birdemic

Reputation: 31

Passing variable to Linux bash command parameter

I have the following bash script thowring exception: "cut: option requires an argument -- 'f'".

It would cut out the 5th colunm from /etc/passwd, separated by ':' character.

How should I pass the $variable to the option's parameter?

variable=5; cut -d':' -f$variable < /etc/passwd

Upvotes: 0

Views: 2444

Answers (2)

Diego Torres Milano
Diego Torres Milano

Reputation: 69396

To avoid that, use

set -o nounset

and then, if variable is unset you'll receive

bash: variable: unbound variable

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247210

You get this when $variable is empty:

$ variable=
$ cut -d: -f$variable </etc/passwd
cut: option requires an argument -- 'f'
Try 'cut --help' for more information.

2 suggestions:

  1. ensure the variable has a value
  2. quote your variables, and in this case, separate the option from the argument: at least you'll get a saner error when the value is empty

    $ cut -d : -f "$variable" </etc/passwd
    cut: fields are numbered from 1
    Try 'cut --help' for more information.
    

Upvotes: 1

Related Questions