in循环中的bash basename语法错误

时间:2013-10-25 13:03:00

标签: bash

我有一个简单的脚本:

for photo in $full_path/*.jpg; do
    $b_photo=$(basename $photo)
    echo $b_photo
done

它是我正在尝试做的简化形式,但这给了我这样的错误:

./foo.sh: line 334: =foobar.jpg: command not found

2 个答案:

答案 0 :(得分:5)

使用var=$(command)分配变量,并将其与$var(或更好,${var})一起使用:

for photo in $full_path/*.jpg; do
    b_photo=$(basename $photo)       <------ b_photo=$() instead of $b_photo=$()
    echo $b_photo                                                   ^
done

注意你可以直接写:

for photo in $full_path/*.jpg; do
    basename "$photo"
done

答案 1 :(得分:3)

除问题pointed out by fedorqui外,如果basename $photo包含空格,则$photo会出错:

 $ photo="directory/file name"
 $ basename $photo
 file

如果$photo-

开头,也会出错
$ photo="-directory/file"
$ basename $photo
basename: illegal option -- d
usage: basename string [suffix]
       basename [-a] [-s suffix] string [...]

你可以写:

for photo in "$full_path"/*.jpg; do
    basename -- "$photo"
done

但是执行此任务的简单方法(在与模式匹配的目录中打印文件名到标准输出,每行一个)将切换到目录并使用printf

{ cd -- "$full_path" && printf "%s\n" *.jpg }