bash 标志设置的变量不能被另一个命令使用

问题描述

我编写了以下 bash 脚本来将 CSV 文件的顶行和底行打印为表格。

#!/usr/bin/env bash   
                                                                                                            
# Default argument                                                                                          
num=10                                                                                                      
                                                                                                            
# Get flag values                                                                                           
while getopts ":n:" opt; do                                                                                 
   case $opt in                                                                                             
       n)                                                                                                   
           # Get argument values                                                                            
           num=$OPTARG                                                                                      
           # Print to check                                                                                 
           echo $num                                                                                        
           ;;                                                                                               
   esac                                                                                                     
done                                                                                                        
                                                                                                            
column -t -s,<(head -n $((num+1)) $1) <(tail -n $num $1)                                                  
                             

认情况下,我将顶部和底部行的数量设置为 10。脚本在没有 -n 标志的情况下运行良好。但是,当我指定标志时,我的 echo 显示 num 已正确设置,但出现以下错误

tail: option requires an argument -- 'n'
Try 'tail --help' for more @R_981_4045@ion.
head: option requires an argument -- 'n'
Try 'head --help' for more @R_981_4045@ion.
                            

numtail 似乎都没有看到 head。即使我在最后一个命令之前贴上 echo,我也可以看到 num 设置正确,但显然有些问题。为什么我会收到这些错误

PS 我使用 this CSV file 进行测试。


在 Cyrus 的有用建议的提示下,我在调试模式下得到以下信息(其中 ht 是我的脚本名称):

./ht -n 5 sealevels.csv 
+ num=10
+ getopts :n: opt
+ case $opt in
+ num=5
+ echo 5
5
+ getopts :n: opt
+ echo 5
5
+ column -t -s,/dev/fd/63 /dev/fd/62
++ head -n 6 -n
++ tail -n 5 -n
head: option requires an argument -- 'n'
Try 'head --help' for more @R_981_4045@ion.
tail: option requires an argument -- 'n'
Try 'tail --help' for more @R_981_4045@ion.

额外的尾随 -n 来自哪里?!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)