我编写了一个shell脚本来复制当前日期的文件,并将它们放在目标文件夹中,并带有当前日期名称,目标文件夹路径包含变量。当我手动运行cd或cp命令时,此路径正常,但在shell脚本中,在通过cp复制时,无法识别带变量的目录。
d=`date +%b' '%d`
td=`date +%d%b%Y`
cd /filenet/shared/logs
mkdir $td
cd $td
mkdir icn02 icn03 GC cpe01 cpe02 cpe03 cpeb01 cpeb02 icn01 css01 css02 http01 http02 http03
ssh hostname <<'ENDSSH'
cd /<some_path>
ls -ltrh | grep "$d" | awk {'print $9'} | xargs cp -t /filenet/shared/logs/"${td}"/GC
ENDSSH
错误
-ksh[2]: td: not found [No such file or directory]
cp: failed to access ‘/filenet/shared/logs//GC’: No such file or directory
答案 0 :(得分:1)
我建议更换
$(td)
与
${td}
答案 1 :(得分:1)
此脚本的更正版本可能更像以下内容:
#!/usr/bin/env bash
# ^^^^- ksh93 also allowable; /bin/sh is not.
d=$(date '+%b %d') || exit
td=$(date '+%d%b%Y') || exit
cd /filenet/shared/logs || exit
mkdir -p -- "$td" || exit
cd "$td" || exit
mkdir -p -- icn02 icn03 GC cpe01 cpe02 cpe03 cpeb01 cpeb02 icn01 css01 css02 http01 http02 http03 || exit
# these should only fail if you're using a shell that isn't either bash or ksh93
d_q=$(printf '%q' "$d") || exit
td_q=$(printf '%q' "$td") || exit
ssh hostname "bash -s ${d_q} ${td_q}" <<'ENDSSH'
d=$1
td=$2
cd /wherever || exit
find . -name "*${d}*" -exec cp -t "/filenet/shared/logs/${td}/GC" -- {} +
ENDSSH
注意:
<<'ENDSSH'
)时,heredoc中的扩展不受尊重。要复制变量,请将它们移出带外 - 在这里,我们使用printf %q
生成我们的eval
值的转义副本 - 安全,并使用bash -s
来放置那些在shell命令行中{$1
和$2
)。ls
。