为unix中的文件提取ls -l输出的起始字符

时间:2016-09-17 17:16:48

标签: bash shell grep wildcard

以下是文件名:

-rwxrwxrwx 1 user1 users 268 Sep 16 18:06 script

在这里grep第一个角色应该是什么命令?

基于我想要推断该项目是文件,目录还是软链接。

我们可以使用通配符" ^"要获得此信息吗?

1 个答案:

答案 0 :(得分:5)

这是错误的方式来判断某些东西是否是符号链接; you should never parse the output of ls, which is meant for human consumption only。相反,使用test原语:

for name in *; do
  if   test -L "$name"; then echo "symlink:           $name"
  elif test -f "$name"; then echo "regular file:      $name"
  elif test -d "$name"; then echo "directory:         $name"
  elif test -b "$name"; then echo "block device:      $name"
  elif test -c "$name"; then echo "character device:  $name"
  elif test -p "$name"; then echo "named pipe (FIFO): $name"
  elif test -S "$name"; then echo "socket:            $name"
  else                       echo "other:             $name"
  fi
done

上述内容也可以写成[ -L "$name" ][ -f "$name" ]等;就像有一个名为test的shell内置命令和一个名为/usr/bin/test的可执行文件一样,还有一个名为[的shell内置命令和一个像/usr/bin/[这样的可执行文件(行为方式完全相同,之外,要求其最后一个参数为])。

回答你的文字问题,解决如何最好地解决你的实际/潜在问题:

在shell中的字符串中有内容后,您可以执行参数扩展以获取第一个字符:

s=abc # or s=$(...some command here...), or so forth
echo "${s:0:1}" # this returns "a"

要获取流的第一个字符(例如来自管道命令的stdout),您只需使用head -c 1

echo "abc" | head -c 1 # this also returns "a"; echo can be replaced with any other command