大网数据广告活动
服务器运维问答

Linux shell script "No such file or directory"

· 52CE 我爱测

I have created a shell script to complete 3 simple tasks (zip a directory, rename the final file and delete the source directory). The script source is below: #!/bin/bash if [[ $2 == *"/data/"* ]] then src= $2"/*"; dest= $1".zip"…

问题原文

原帖链接 · h2odev · CC BY-SA 3.0

I have created a shell script to complete 3 simple tasks (zip a directory, rename the final file and delete the source directory). The script source is below:

#!/bin/bash
if [[ $2 == *"/data/"* ]]
then
    src= $2"/*";
    dest= $1".zip";

    # Just for test
    echo $src;

    # Commented for now
    #zip -r -j $dest $src
    #mv $dest $1
    #rm -rf $2
else
    echo "Invalid arguments";
fi

When I run the script above with these parameters I have with error:

./scriptzip.sh /data/file-new /data/file-old

./scriptzip.sh: line 4: /data/file-old/*: No such file or directory
./scriptzip.sh: line 5: /data/file-new.zip: No such file or directory

How can prevent the shell to test a variable for "directory like" string? There is any way to skip that?

已采纳解答

原帖链接 · thrig · CC BY-SA 3.0

The space is significant in the shell, as that's what divides the tokens in commands such as echo foo bar or worse rm -rf /some/where /. Hence, assignment must not include spaces around the =:

foo=/etc/*
echo $foo

Variables may also need quoting, depending on exactly what you want to happen for here glob expansion and also word splitting (incorrect word splitting to rm can result in unexpected (and hilarious) filesystem cleanups).

echo "$foo"

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-08-17)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。