如何在Linux壳脚本中使用的变量运行轨迹(How to traverse path using v

2019-11-04 14:07发布

我写了一个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

Answer 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' ),在定界符内的扩展将不被执行。 要复制整个变量,移动出来的带外-在这里,我们使用printf %q来产生我们的价值观它们逃脱副本eval -保险箱,并使用bash -s把那些在shell命令行( $1$2 )。
  • 永远不要用grep或解析的输出ls


Answer 2:

我建议更换

$(td)

${td}


文章来源: How to traverse path using variable in linux shells script