Bash:将unix命令的结果存储到while循环中的变量时出错 [英] Bash: Error when storing result of unix command to variable in while loop

查看:79
本文介绍了Bash:将unix命令的结果存储到while循环中的变量时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下名为test.sh的脚本:

I have the following script called test.sh:

echo "file path is : $1"
path=$1
while read -r line 
do
    num=$($line | tr -cd [:digit:])
    echo num
done < $path
exit 0

我正在尝试获取存储为$ path的文件的每一行开头的数字.最终结果将是遍历每一行,抓住数字,如果小于2,则将其从文件中删除.

I am attempting to grab the digit at the start of each line of the file stored as $path. the end result will be to loop over each line, grab the digit and remove it from the file if it is less than 2.

每次运行此循环时,都会出现错误"./test.sh:第5行::命令未找到.我在while循环的哪一部分做错了?还是与tr命令有关?

Every time i run this loop i get the error "./test.sh: line 5: : command not found. What part of the while loop am I doing wrong? Or is it something to do with the tr command?

推荐答案

我可以发现您的脚本有一些错误:

I can spot a few things wrong with your script:

#!/bin/bash

echo "file path is : $1"
path=$1
while read -r line 
do
    num=$(tr -cd '[:digit:]' <<<"$line") # use here string to "echo" variable to tr
    echo "$num" # added quotes and $
done < "$path" # added quotes, changed $dest to $path

总结:

  • cmd <<<"$var"(此处为字符串)是bash内置的,用于替代echo "$var" | cmd.我在脚本顶部添加了#!/bin/bash,因为我正在使用仅bash的功能.
  • 我已引用了您的变量,以防止出现单词拆分和glob扩展问题.
  • 我假设您确实打算在最后一行使用$path(尽管我可能错了).
  • 最后,无需在脚本结尾处添加exit 0.
  • cmd <<<"$var" (here string) is a bash built-in designed as a replacement for echo "$var" | cmd. I added #!/bin/bash to the top of the script, as I am using this bash-only feature.
  • I have quoted your variables to prevent problems with word splitting and glob expansion.
  • I made the assumption that you really meant to use $path on the last line (though I may be wrong).
  • Finally, there's no need to exit 0 at the end of your script.

这篇关于Bash:将unix命令的结果存储到while循环中的变量时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆