【问题标题】:How to traverse path using variable in linux shells script如何在 linux shells 脚本中使用变量遍历路径
【发布时间】:2017-12-15 20:48:08
【问题描述】:

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

【问题讨论】:

  • ksh 不是 bash。
  • 我用过#!/bin/ksh echo $0 bash
  • heredoc 中的 $d 计算结果为名为 dremote 变量,而不是该名称的 local 变量。
  • 不要将grep 传递给awk... | grep pattern | awk '{cmd}'... | awk '/pattern/{cmd}' 相同。

标签: linux bash shell unix scripting


【解决方案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

注意:

  • 当使用引用的 heredoc (&lt;&lt;'ENDSSH') 时,不支持 heredoc 中的扩展。要复制变量,请将它们移出带外——在这里,我们使用printf %q 生成我们的值的转义副本,这些副本是eval-安全的,并使用bash -s 将它们放在shell命令行中( $1$2)。
  • Never, ever grep or parse the output of ls

【讨论】:

  • 谢谢你,Charles,我会试试这个,让大家知道。
【解决方案2】:

我建议更换

$(td)

${td}

【讨论】:

  • 我也试过了放入脚本时
  • OP 似乎已经以删除使这个答案有意义的上下文的方式编辑了这个问题。
猜你喜欢
  • 1970-01-01
  • 2021-05-31
  • 1970-01-01
  • 2021-02-18
  • 2012-02-15
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多