如何在linux shells脚本中使用变量遍历路径 [英] How to traverse path using variable in linux shells script
本文介绍了如何在linux shells脚本中使用变量遍历路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了一个 shell 脚本来复制当前日期的文件并将它们放在具有当前日期名称的目标文件夹中,目标文件夹路径包含变量.当我手动运行 cd 或 cp 命令时,此路径工作正常,但在 shell 脚本中,通过 cp 复制时,无法识别带有变量的目录.
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
错误
-ksh[2]: td: not found [No such file or directory]
cp: failed to access ‘/filenet/shared/logs//GC’: No such file or directory
推荐答案
此脚本的更正版本可能看起来更像以下内容:
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
注意:
- 当使用引用的 heredoc (
<<'ENDSSH'
) 时,不支持 heredoc 中的扩展.要复制变量,将它们移到带外——在这里,我们使用printf %q
来生成我们的值的转义副本,这些副本是eval
安全的,并使用bash -s
将它们放在 shell 命令行中($1
和$2
). - 永远不要grep或解析
ls
的输出.
- 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 %q
to generate escaped copies of our values which areeval
-safe, and usebash -s
to put those in the shell command line ($1
and$2
). - Never, ever grep or parse the output of
ls
.
这篇关于如何在linux shells脚本中使用变量遍历路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文