【问题标题】:How to use bash variable prefixes under sh, ksh, csh如何在sh、ksh、csh下使用bash变量前缀
【发布时间】:2020-11-02 16:15:13
【问题描述】:

我有 bash 脚本,它检查某些文件的存在以及内容的格式是否有效。它使用变量前缀,因此我可以轻松添加/删除新文件而无需进一步调整。

问题是我需要在没有 bash 的 AIX 服务器上运行它。我已经调整了脚本,除了带有变量前缀的部分。经过一些尝试,我迷失了方向,不知道如何正确迁移以下代码,使其在 sh ($(echo ${!ifile_@})) 下运行。或者我有 kshcsh 如果普通 sh 不是一个选项。

提前感谢您的任何帮助/提示

#!/bin/sh
# Source files
ifile_one="/path/to/file/one.csv"
ifile_two="/path/to/file/two.csv"
ifile_three="/path/to/file/three.csv"
ifile_five="/path/to/file/four.csv"

min_columns='10'
existing_files=""
nonexisting_files=""
valid_files=""
invalid_files=""

# Check that defined input-files exists and can be read.
for input_file in $(echo ${!ifile_@})
do
    if [ -r ${!input_file} ]; then
        existing_files+="${!input_file} "
    else
        nonexisting_files+="${!input_file} "
    fi
done
echo "$existing_files"
echo "$nonexisting_files"

# Check that defined input files have proper number of columns. 
for input_file_a in $(echo "$existing_files")
do
    check=$(grep -v "^$" $input_file_a | sed 's/[^;]//g' | awk -v min_columns="$min_columns" '{ if (length == min_columns) {print "OK"} else {print "KO"} }' | grep -i KO)
    if [ ! -z "$check" ]; then
        invalid_files+="${input_file_a} "
    else
        valid_files+="${input_file_a} "
    fi
done
echo "$invalid_files"
echo "$valid_files"

Bash 返回(四个 ECHO 的)预期输出:

/path/to/file/one.csv /path/to/file/two.csv /path/to/file/three.csv
/path/to/file/four.csv

/path/to/file/three.csv
/path/to/file/one.csv /path/to/file/two.csv

ksh/sh 抛出:

./report.sh[14]: "${!ifile_@}": 0403-011 The specified substitution is not valid for this command.

【问题讨论】:

  • 您可以使用 ksh 数组代替前缀参数扩展。
  • 在 Aix 中,/bin/ksh 不支持此功能,但 /bin/ksh93 支持。
  • @LorinczyZsigmond 谢谢,试过了,但它返回以下内容作为“valid_files”的内容:input_file input_file input_file input_file input_file input_file
  • 好吧,另一个想法:set | grep '^ifile_' | while IFS='=' read V W; do printf "$V = $W\n"; done
  • @Hakun1n :我认为将 bash 程序转换为 sh 是不必要的痛苦,除非它真的只使用 sh 中也存在的简单 shell 工具。我也不会使用csh,因为在 csh 中编程也相当不愉快。因此我会用 ksh93 重写它。想想“重写”,而不是“转换”,你的生活会更轻松。另一种可能性是用 Perl 编写所有内容。

标签: bash variables ksh


【解决方案1】:

感谢@Benjamin W. 和@user1934428,ksh93 数组就是答案。 所以下面的代码可以根据需要为我工作。

#!/bin/ksh93
typeset -A ifile
ifile[one]="/path/to/file/one.csv"
ifile[two]="/path/to/file/two.csv"
ifile[three]="/path/to/file/three.csv"
ifile[whatever]="/path/to/file/something.csv"

existing_files=""
nonexisting_files=""

for input_file in "${!ifile[@]}"
do
    if [ -r ${ifile[$input_file]} ]; then
        existing_files+="${ifile[$input_file]} "
    else
        nonexisting_files+="${ifile[$input_file]} "
    fi
done

【讨论】:

    猜你喜欢
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多