Shell脚本,将命令值保存到变量[重复]

hrysbysz  于 12个月前  发布在  Shell
关注(0)|答案(1)|浏览(110)

此问题已在此处有答案

Command not found error in Bash variable assignment(6个回答)
4天前关闭。
我试图在同一行中打印VARI的值,后面跟着一个逗号,这样我就可以拥有这些值的csv文件,但我无法保存VARI = 'cat filename | head -1 | cut -d, -f${i}'的值。

i=0
while (( i<130)) ;
do
  if [[ $i -eq 1 ||  $i -eq 9 || $i -eq 12 || $i -eq 23 || $i -eq 25 || $i -eq 29 ]]
  then
    VARI = 'cat filename | head -1 | cut -d, -f${i}'
    echo  "$VARI ,"   
  fi
  let i=$i+1;
done

预期产出为

4,abc,5,8,xyz,9

请让我知道我做错了什么,谢谢!

snvhrwxg

snvhrwxg1#

使用反引号(或$(),可以嵌套),而不是单引号:

VARI=`cat filename | head -1 | cut -d, -f${i}` # or:
VARI=$(cat filename | head -1 | cut -d, -f${i})

确保变量名、等号和变量值之间没有空格。

VAR = x # executes program "VAR" with 2 parameters: "=" and "x"
VAR =x  # executes program "VAR" with a single parameter: "=x"
VAR= x  # executes program "x" with environment variable "VAR" set to an empty value
VAR=x   # assigns value "x" to shell variable "VAR"

参考资料:2.10.2 POSIX. 1 -2017规范的Shell语法规则。

相关问题