unix - 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
解决方案
它不起作用的原因是因为变量只替换在双引号 ( "
) 内,而不是单引号 ( '
),并且您使用的是单引号:
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 等)。
推荐阅读
- javascript - HTML 多个不同的“全选”复选框
- c# - 使用asp.net核心的控制器和路由问题
- sql - 递归 SQLite 查询
- python - 如何使用 Pandas/in Python 重新格式化索引中的日期
- sql - 添加序列的第一个和最后一个日期
- javascript - 使用从表上的查询获得的数据动态更改 html 选择表单元素中的选项
- pythonanywhere - ImportError 使用 pythonanywhere 导入 Web3
- ios - 将调试器上的 xcode 调试堆栈跟踪导出到崩溃文件
- php - 使用 jquery-confirm 编辑表单
- javascript - React js Apollo 解构结果