问题
I wrote a shell script to copy current date's files and place them in target folder with current date name, target folder path contains variable. This path works fine when i manually run the cd or cp command, but in shell script, while copying through cp, directory with variable is not recognized.
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
Error
-ksh[2]: td: not found [No such file or directory]
cp: failed to access ‘/filenet/shared/logs//GC’: No such file or directory
回答1:
A corrected version of this script may look more like the following:
#!/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
Note:
- When using a quoted heredoc (
<<'ENDSSH'), expansions within the heredoc are not honored. To copy variables across, move them out-of-band -- here, we useprintf %qto generate escaped copies of our values which areeval-safe, and usebash -sto put those in the shell command line ($1and$2). - Never, ever grep or parse the output of ls.
回答2:
I suggest to replace
$(td)
with
${td}
来源:https://stackoverflow.com/questions/47839661/how-to-traverse-path-using-variable-in-linux-shells-script