bash脚本出错 - 为变量赋值

时间:2014-12-20 09:16:45

标签: linux bash ubuntu

我正在尝试创建一个小脚本,它会在$2目录中为我提供没有$3首字母和$1姓氏的文件名

我有这段代码

#!/bin/bash
TOTFILES=find "$1" -maxdepth 1 -type f -exec basename {} ';' | wc -l
find "$1" -maxdepth 1 -type f -exec basename {} ';' | sort |
    head -n (( TOTFILES-$3 )) | tail -n (( TOTFILES-$3-$2 ))

我的主要问题是我不能用该长行的输出分配TOTFILES。

我认为如果我可以分配该值,它将起作用 (希望如此):)

PS: 我不知道我是否使用过

(( TOTFILES-$3 ))

是的,要获得价值。

感谢您的快速回答。 现在我遇到了一个新问题;我猜(( ))不是获得号码的正确方法

./middleFiles: line 5: syntax error near unexpected token `('
./middleFiles: line 5: `find "$1" -maxdepth 1 -type f -exec basename {} ';' | sort | head -n (( TOTFILES-$3 ))  | tail -n (( TOTFILES-$3-$2 ))'

3 个答案:

答案 0 :(得分:3)

Command substitution分配命令的输出:

TOTFILES=$(find "$1" -maxdepth 1 -type f -exec basename {} ';' | wc -l)

Arithmetic expansion会告诉您headtail的参数:

head -n $(( $TOTFILES - $3 ))

答案 1 :(得分:0)

我相信你需要围绕你想要评估的表达式进行反引号。

TOTFILES=`find "$1" -maxdepth 1 -type f -exec basename {} ';' | wc -l`

有关详细信息,请参阅this answer

答案 2 :(得分:-2)

我认为最好的方法是将文件名分配给数组。根据您的代码,您只需要depth = 1这么简单的ls技巧就可以完成工作

#!/bin/bash

TOTFILES=($(ls -p $1 | grep -v / | sort -n)

# and you can use the array like this
for file in ${TOTFILES[*]};do 
    echo $file;
done
# leave you to get a subset of the ${ToTFILES}
# refer to http://stackoverflow.com/questions/1335815/how-to-slice-an-array-in-bash
相关问题