在执行的命令中使用 BASH 脚本变量
Using a BASH script variable into an executed command
有人可以帮忙解决这个问题吗,因为我似乎找不到解决方案。我有以下运行良好的脚本:
#!/bin/bash
#Checks the number of lines in the userdomains file
NUM=`awk 'END {print NR}' /etc/userdomains.hristian`;
echo $NUM
#Prints out a particular line from the file (should work with $NUM eventually)
USER=`sed -n 4p /etc/userdomains.hristian`
echo $USER
#Edits the output so that only the username is left
USER2=`echo $USER | awk '{print $NF}'`
echo $USER2
但是,当我用变量 $NUM 替换第 12 行的 4 时,它不起作用:
USER=`sed -n $NUMp /etc/userdomains.hristian`
我尝试了引号和 ${} 的多种不同组合,但是其中 none 似乎有效,因为我是 BASH 新手。请帮助:)
我不确定你已经尝试了什么,但这对我有用:
$ cat out
line 1
line 2
line 3
line 4
line 5
$ num=4
$ a=`sed -n ${num}p out`
$ echo "$a"
line 4
要清楚,这里的问题是您需要在 sed 命令中将 $num
的扩展与 p
分开。这就是花括号的作用。
请注意,我使用的是小写变量名。大写字母应保留供 shell 使用。我还建议使用更现代的 $()
语法进行命令替换:
a=$(sed -n "${num}p" out)
sed 命令周围的双引号不是必需的,但它们不会造成任何伤害。一般来说,围绕扩展使用它们是个好主意。
大概您问题中的脚本是一个学习练习,这就是您单独完成所有步骤的原因。作为记录,您可以像这样一次性完成所有事情:
awk 'END { print $NF }' /etc/userdomains.hristian
在END
块中,仍然可以访问文件中最后一行的值,因此可以直接打印最后一个字段。
您尝试计算变量 $NUMp
而不是 $NUM
。试试这个:
USER=`sed -n ${NUM}p /etc/userdomains.hristian`
有人可以帮忙解决这个问题吗,因为我似乎找不到解决方案。我有以下运行良好的脚本:
#!/bin/bash
#Checks the number of lines in the userdomains file
NUM=`awk 'END {print NR}' /etc/userdomains.hristian`;
echo $NUM
#Prints out a particular line from the file (should work with $NUM eventually)
USER=`sed -n 4p /etc/userdomains.hristian`
echo $USER
#Edits the output so that only the username is left
USER2=`echo $USER | awk '{print $NF}'`
echo $USER2
但是,当我用变量 $NUM 替换第 12 行的 4 时,它不起作用:
USER=`sed -n $NUMp /etc/userdomains.hristian`
我尝试了引号和 ${} 的多种不同组合,但是其中 none 似乎有效,因为我是 BASH 新手。请帮助:)
我不确定你已经尝试了什么,但这对我有用:
$ cat out
line 1
line 2
line 3
line 4
line 5
$ num=4
$ a=`sed -n ${num}p out`
$ echo "$a"
line 4
要清楚,这里的问题是您需要在 sed 命令中将 $num
的扩展与 p
分开。这就是花括号的作用。
请注意,我使用的是小写变量名。大写字母应保留供 shell 使用。我还建议使用更现代的 $()
语法进行命令替换:
a=$(sed -n "${num}p" out)
sed 命令周围的双引号不是必需的,但它们不会造成任何伤害。一般来说,围绕扩展使用它们是个好主意。
大概您问题中的脚本是一个学习练习,这就是您单独完成所有步骤的原因。作为记录,您可以像这样一次性完成所有事情:
awk 'END { print $NF }' /etc/userdomains.hristian
在END
块中,仍然可以访问文件中最后一行的值,因此可以直接打印最后一个字段。
您尝试计算变量 $NUMp
而不是 $NUM
。试试这个:
USER=`sed -n ${NUM}p /etc/userdomains.hristian`