Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

bash - How to traverse path using variable in linux shells script

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

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

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...