将变量传递给Linux bash命令参数

时间:2018-03-05 21:12:10

标签: linux bash parameters command

我有以下bash脚本提出异常:“cut:option需要一个参数 - 'f'”。

它会从/ etc / passwd中删除第5个colunm,用':'字符分隔。

我应该如何将$变量传递给选项的参数?

Cities:
id__| country__
--------------
_1__| 1000
_2__| 1001
_3__| 1002

Translates:
id__ | city_id  |      name       | __lang__ | _order_
-------------------------------------------------------
1____|     1    | Dnipro          | en       | 2
2____|     1    | Dnipropetrovsk  | en       | 1
3____|     1    | Ekaterinoslav   | en       | 3

2 个答案:

答案 0 :(得分:1)

$variable为空时,你会得到这个:

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

2条建议:

  1. 确保变量具有值
  2. quote your variables,在这种情况下,将选项与参数分开:至少当值为空时,你会得到一个更安全的错误

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

答案 1 :(得分:0)

为避免这种情况,请使用

set -o nounset

然后,如果variable未设置,您将收到

bash: variable: unbound variable