首页 > 解决方案 > tcsh 在 shell 脚本中传递变量

问题描述

我在 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

标签: unixawkpipecatcsh

解决方案


它不起作用的原因是因为变量只替换在双引号 ( ") 内,而不是单引号 ( '),并且您使用的是单引号:

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 等)。


推荐阅读