首页 > 解决方案 > Linux中是否有任何方法可以显示并排多次使用的命令的输出?

问题描述

我是 Linux 和 Shell 脚本的菜鸟,我正在尝试编写一个 shell 脚本,该脚本将根据传递的命令行参数显示目录列表。它将接受 4 个位置参数,即 F、D、T 和 P 并相应地显示。

样本输入和输出:

$ ./list.sh F D T P 
File name       date        time        permission 
-------------   ------      -----       --------------- 
Filename1       date        time        permission 
Filename2       date        time        permission 

Total no. of files : <total number> 
Total no of normal file : <number> 
Total no of directory : <number>

争论可能会被打乱。我试图编写一个能够完成工作但无法按我想要的方式显示的 shell 脚本。

#!/bin/bash

args=("$@") # Storing all the positional args into an array
n=0
x=0

while [ $n -ne 4 ]
do
    case "${args[$n]}" in 
        F)  argsVal[$x]=9 ;;
        D)  argsVal[$x]=6 ;;
        T)  argsVal[$x]=8 ;;
        P)  argsVal[$x]=1 ;;
        *)  echo "Invalid Option" ;;
    esac
    n=`expr $n + 1`
    x=`expr $x + 1`
done

n=0
while [ $n -ne 4 ]
do 
    case "${argsVal[$n]}" in
        
    1) echo -e "Permissions(P)\t\c" ;;

    6) echo -e "Date(D)\t\c" ;;

    8) echo -e "Time(T)\t\c" ;;

    9) echo -e "FileNames(F)\t\c" ;;
    
    *) ;;
    esac
    n=`expr $n + 1`
done

echo -e "\n"

n=0
while [ $n -ne 4 ]
do 
    case "${argsVal[$n]}" in
    
    1) 
    awk '{print $1}' listout ;;

    6) 
    awk '{print $6,$7}' listout ;;

    8)
    awk '{print $8}' listout ;;

    9)
    awk '{print $9}' listout ;;
    
    *) ;;
    esac
    n=`expr $n + 1`
done

输出是:

Permissions(P)  Date(D) Time(T) FileNames(F)

-rw-r--r--
-rwxr--r--
-rwxr--r--
-rwxr--r--
-rwxr--r--
Jun 18
Jun 19
Jun 6
Jun 18
Jun 6
22:04
12:04
20:45
22:32
21:17
listout
list.sh
script.sh
test1.sh
validvoter.sh

标签: bashshell

解决方案


printf用命令试试:

#!/bin/bash

while [ $# -gt 0 ] ; do
  case $1 in

    F) 
      arg="$arg\$9, " 
      tit=("${tit[@]}" "File name (F)")
      unl=("${unl[@]}" "-------------")
      fmt="$fmt%-35s"
      ;;
    P) 
      arg="$arg\$1, " 
      tit=("${tit[@]}" "Permissions (P)")
      unl=("${unl[@]}" "---------------")
      fmt="$fmt%-17s"
      ;;
    T) 
      arg="$arg\$8, "
      tit=("${tit[@]}" "Time (T)")
      unl=("${unl[@]}" "--------")
      fmt="$fmt%-10s"
      ;;
    D) 
      arg="$arg\$6\" \"\$7, "
      tit=("${tit[@]}" "Date (D)")
      unl=("${unl[@]}" "--------")
      fmt="$fmt%-10s"
      ;;
    *)
      echo "invalid option $1"
      exit 1
  esac
  shift
done

if [ -z "$arg" ] ; then
  echo "missing options"
  exit 2
fi

arg=${arg%, } # remove trailing comma and space from $arg

printf "$fmt\\n" "${tit[@]}"
printf "$fmt\\n" "${unl[@]}"

ls -l | grep -v '^total' > listout

grep -v "^total" listout | 
  awk "{ printf \"$fmt\\n\", $arg}"

tf=$(cat listout | wc -l)
tnf=$(grep '^-' listout | wc -l)
td=$(grep '^d' listout | wc -l)

echo
echo "Total number of files:           $tf"
echo "Total number of normal files:    $tnf"
echo "Total number of directories:     $td"

推荐阅读