我有一个简单的脚本:
for photo in $full_path/*.jpg; do
$b_photo=$(basename $photo)
echo $b_photo
done
这是我正在尝试做的简化形式,但这给了我这样的错误:
./foo.sh: line 334: =foobar.jpg: command not found
我有一个简单的脚本:
for photo in $full_path/*.jpg; do
$b_photo=$(basename $photo)
echo $b_photo
done
这是我正在尝试做的简化形式,但这给了我这样的错误:
./foo.sh: line 334: =foobar.jpg: command not found
分配变量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
除了fedorqui 指出的问题,如果包含空格basename $photo
会出错:$photo
$ photo="directory/file name"
$ basename $photo
file
$photo
如果以 a 开头也会出错-
:
$ 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 }