Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
421 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 use printf %q to generate escaped copies of our values which are eval-safe, and use bash -s to put those in the shell command line ($1 and $2).
  • Never, ever grep or parse the output of ls.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...