Bash脚本单独执行行正常,整体运行报语法错误求助
Bash脚本单独行正常但整体运行语法错误排查
你的脚本代码如下:
#!/bin/bash col1=$( ls -l | head | awk '{print $1}') echo $col1 col2=$(ls -l | head | awk '{print $2}') echo $col2 paste <(echo "$col1") <(echo "$col2") | column --table --output-separator "|" | cat -s -n
报错信息(翻译自截图)
line 7: syntax error near unexpected token
<' line 7:paste <(echo "$col1") <(echo "$col2") | column --table --output-separator "|" | cat -s -n '
问题原因
这个错误是因为进程替换(<(...)这种语法)是Bash专属特性,你的脚本可能被非Bash的shell(比如sh)执行了——哪怕脚本开头写了#!/bin/bash,如果用sh script.sh命令运行,系统会强制用sh解释,而sh不支持进程替换语法。
解决办法
用Bash直接运行脚本
给脚本添加执行权限后直接运行:chmod +x your_script.sh ./your_script.sh或者直接指定Bash解释器:
bash your_script.sh替换进程替换语法(兼容更多shell)
用临时文件替代进程替换,写法如下:#!/bin/bash # 提取列到临时文件 ls -l | head | awk '{print $1}' > /tmp/col1.tmp ls -l | head | awk '{print $2}' > /tmp/col2.tmp # 合并处理 paste /tmp/col1.tmp /tmp/col2.tmp | column --table --output-separator "|" | cat -s -n # 清理临时文件 rm /tmp/col1.tmp /tmp/col2.tmp更高效的写法(避免重复执行ls)
直接用awk一次提取两列,省去多次调用ls和中间变量,更高效也避免语法兼容问题:#!/bin/bash ls -l | head | awk '{printf "%s|%s\n", $1, $2}' | cat -s -n # 或者用column格式化: ls -l | head | awk '{print $1, $2}' | column --table --output-separator "|" | cat -s -n
内容的提问来源于stack exchange,提问作者user96368
相关产品推荐
相关产品推荐

