首页 > 解决方案 > 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 information.
head: option requires an argument -- 'n'
Try 'head --help' for more information.
                            

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

PS 我使用这个 CSV 文件进行测试。


在 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 information.
tail: option requires an argument -- 'n'
Try 'tail --help' for more information.

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

标签: bashtailheadgetopts

解决方案


推荐阅读