简体   繁体   English

在bash脚本循环中打印cat语句的输出

[英]Print output of cat statement in bash script loop

I'm trying to execute a command for each line coming from a cat command. 我正在尝试为来自cat命令的每一行执行命令。 I'm basing this on sample code I got from a vendor. 我的基础是我从供应商处获得的示例代码。

Here's the script: 这是脚本:

for tbl in 'cat /tmp/tables'
do
   echo $tbl
done

So I was expecting the output to be each line in the file. 所以我期待输出是文件中的每一行。 Instead I'm getting this: 相反,我得到了这个:

cat
/tmp/tables

That's obviously not what I wanted. 这显然不是我想要的。

I'm going to replace the echo with an actual command that interfaces with a database. 我将用一个与数据库连接的实际命令替换echo。

Any help in straightening this out would be greatly appreciated. 任何帮助纠正这一点将不胜感激。

You are using the wrong type of quotes. 您使用的是错误的报价类型。

You need to use the back-quotes rather than the single quote to make the argument being a program running and piping out the content to the forloop. 您需要使用后引号而不是单引号来使参数成为程序运行并将内容输出到forloop。

for tbl in `cat /tmp/tables` 
do 
    echo "$tbl"
done

Also for better readability (if you are using bash), you can write it as 另外为了更好的可读性(如果你使用bash),你可以把它写成

for tbl in $(cat /tmp/tables) 
do 
    echo "$tbl"
done

If your expectations are to get each line (The for-loops above will give you each word), then you may be better off using xargs , like this 如果你的期望是获得每一行(上面的for循环会给你每个单词),那么你可能最好使用xargs ,就像这样

cat /tmp/tables | xargs -L1 echo

or as a loop 或作为循环

cat /tmp/tables | while read line; do echo "$line"; done

With while loop: 使用while循环:

while read line
do
echo "$line"
done < "file"

The single quotes should be backticks: 单引号应该是反引号:

for tbl in `cat /etc/tables`

Although, this will not get you output/input by line, but by word. 虽然,这不会让你按行输出/输入,而是按字。 To process line by line, you should try something like: 要逐行处理,您应该尝试以下方法:

cat /etc/tables | while read line
    echo $line
done
while IFS= read -r tbl; do echo "$tbl" ; done < /etc/tables

这个

You can do a lot of parsing in bash by redefining the IFS (Input Field Seperator), for example 例如,您可以通过重新定义IFS(输入字段分隔符)在bash中进行大量解析

IFS="\t\n"  # You must use double quotes for escape sequences. 
for tbl in `cat /tmp/tables` 
do 
    echo "$tbl"
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM