【问题标题】:sh - Build string containing pathssh - 构建包含路径的字符串
【发布时间】:2009-11-23 22:16:40
【问题描述】:

我正在构建一个小型 shell 脚本,用于在各种 unix 系统上查找 cat/man 页面...在 bash 中,我可以通过这样做来构建所有可能的路径:

# default search paths
default=$(echo /usr/{share, local, dpkg, XR11}/man/{man, cat}{1..8})

for path in $default
do 
  ...
done

不幸的是,我不得不使用 sh...我可以用循环构建路径,但这看起来真的很难看...有没有更简洁/更短的方法?

【问题讨论】:

  • 你说的“sh”是什么意思?最初的 bourne shell 已经有一段时间没有出现了。你到底有什么外壳?
  • @bmargulies: waddya 是什么意思?它(Bourne shell)在 Unix(AIX、HP-UX、Solaris)上仍然是标准的。当然不是在 MacOS X 或 Linux 上,其他 shell 在 AIX、HP-UX、Solaris 上可用。但是 Bourne shell 在某些地方仍然是标准的。
  • 这是一个大学项目...该脚本应该能够在尽可能多的 unix 系统上工作,因此决定使用 sh 以获得更大的向后兼容性
  • 顺便说一句,Bash 不会对大括号扩展中的空格感到满意。
  • @bmargulies: ashsashbash 中的sh 兼容模式(尝试以/bin/sh 调用它,看看你得到了什么),busybox 中的外壳等. 等等. 普通的 Bourne shell 仍然是最安全的脚本默认设置。

标签: shell scripting sh


【解决方案1】:

在我的 Linux 系统上,“man -w”打印 nroff 源文件的位置而不是其内容。这样您就可以使用 man 的内部搜索来查找文件 - 就像命令行上的用户一样。

有关更多信息,请参阅“男人男人”。

【讨论】:

  • 只要没有“男人”不知道您需要它查看的地方,它就可以正常工作。然后你开始玩 MANPATH。
【解决方案2】:

这并不可怕:

for dir in share local pdkg XR11; do
  for type in man cat; do
    for n in 1 2 3 4 5 6 7 8; do
      path="/usr/${dir}/man/${type}$n"
      # ...
    done
  done
done

甚至,虽然它不是 DRY,但它是明确且可读的

prefixes="
    /usr/share/man/man /usr/share/man/cat
    /usr/local/man/man /usr/local/man/cat
    /usr/pdkg/man/man  /usr/pdkg/man/cat
    /usr/XR11/man/man  /usr/XR11/man/cat
"
for prefix in $prefixes; do
  for n in 1 2 3 4 5 6 7 8; do
    path="${prefix}$n"
    # ...
  done
done

【讨论】:

    【解决方案3】:

    你可以使用查找

    find /usr/share /usr/local /usr/dpkg /usr/XR11 -type d \( -name "man[0-9]" -o -name "cat[0-9]" -o -name "cat" -o -name "man" \) 
    

    【讨论】:

      【解决方案4】:

      鉴于 Bourne shell,我可能会使用:

      for path in `ls -d /usr/*/man/[mc]a[tn][1-8]`
      do 
          if [ -d $path ]
          then ...
          fi
      done
      

      如果有人恶意创建目录/usr/spoof/man/man3/usr/share/man/mat1/usr/dpkg/man/can2,这只会让你误入歧途,这不太可能,我不会担心。

      【讨论】:

        【解决方案5】:

        你可以使用find:

        find /usr/share /usr/local /usr/dpkg /usr/XR11 -type d -regex '.*/man/\(cat\|man\)[1-8]$'
        

        在我的系统上,我有一堆本地化的 man 页面会被上述内容排除在外,因此您可以这样做:

        find /usr/share /usr/local /usr/dpkg /usr/XR11 -type d -regex '.*/\(cat\|man\)[1-8]$'
        

        【讨论】:

          猜你喜欢
          • 2016-12-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多