Warm tip: This article is reproduced from serverfault.com, please click

unix-tcsh在shell脚本中传递变量

(unix - tcsh passing a variable inside a shell script)

发布于 2020-11-30 11:02:19

我已经在shell脚本中定义了一个变量,我想使用它。由于某种原因,我无法将其传递到需要它的命令行中。

这是我的脚本,在最后几行失败

#! /usr//bin/tcsh -f
if ( $# != 2 ) then
        echo "Usage: jump_sorter.sh <jump> <field to sort on>"
        exit;
endif

set a = `cat $1 | tail -1` #prepares last row for check with loop 
set b = $2 #this is the value last row will be checked for

set counter = 0
foreach i ($a)

if ($i == "$b") then
    set bingo = $counter 
    echo "$bingo is the field to print from $a"
endif

set counter = `expr $counter + 1`
end

echo $bingo #this prints the correct value for using in the command below
cat $1 | awk '{print($bingo)}' | sort | uniq -c | sort -nr #but this doesn't work.

#when I use $9 instead of $bingo, it does work.

请问如何正确地将$ bingo传递到最后一行?

更新:按照Martin Tournoij接受的答案,处理命令中“ $”符号的正确方法是:

cat $1 | awk "{print("\$"$bingo)}" | sort | uniq -c | sort -nr

Questioner
ZakS
Viewed
0
Martin Tournoij 2020-11-30 19:08:23

之所以不起作用,是因为变量仅在双引号(")内而不是单引号('内被替换,并且你使用的是单引号:

cat $1 | awk '{print($bingo)}' | sort | uniq -c | sort -nr

以下应该工作:

cat $1 | awk "{print($bingo)}" | sort | uniq -c | sort -nr

你在这里也有一个错误:

#! /usr//bin/tcsh -f

应该是:

#!/usr/bin/tcsh -f 

请注意,通常不建议使用csh编写脚本。它具有许多怪异之处,并且缺少一些功能(如功能)。除非确实需要使用csh,否则建议使用Bourne shell(/bin/sh,bash,zsh)或脚本语言(Python,Ruby等)代替。