相关疑难解决方法(0)

使用bash逐行读取并保留空间

当我使用"cat test.file"时,它会显示

1
 2
  3
   4
Run Code Online (Sandbox Code Playgroud)

当我使用bash文件时

cat test.file |
while read data
do
    echo "$data"
done
Run Code Online (Sandbox Code Playgroud)

它会显示出来

1
2
3
4
Run Code Online (Sandbox Code Playgroud)

我怎么能像原始测试文件一样制作结果?

bash

61
推荐指数
3
解决办法
6万
查看次数

将stdout和stderr重定向到Function

我需要帮助将输出(stdin和stdout)从系统命令发送到bash函数,同时仍然接受来自参数的输入.类似下面的例子.有人能指出我正确的道路吗?

LogMsg()
{
  DateTime=`date "+%Y/%m/%d %H:%M:%S"`
  echo '*****'$DateTime' ('$QMAKESPEC'): '$1 >> "$LogFile"
  echo $DateTime' ('$QMAKESPEC'): '$1
}

# Already works
LogMsg "This statement is sent directly"

# Wish I could do this:
# Capture both stdout & stderr of a system function to the logfile
# I do not presume that any of the syntax that follows is good
make 2>&1 >(LogMsg)
Run Code Online (Sandbox Code Playgroud)

bash

18
推荐指数
2
解决办法
1万
查看次数

Bash重定向标准输出功能

我有2个日志功能:

log_msg()
{
    if [ ! -e $LOG_FILE ]; then
        touch $LOG_FILE
        chmod 0640 $LOG_FILE
    fi

    echo "$(date +'[%Y-%m-%d %T]') $1" >> $LOG_FILE
}
log_stream()
{
    while read data; do
        printf "$(date +'[%Y-%m-%d %T]') $data" >> $LOG_FILE
    done
}
Run Code Online (Sandbox Code Playgroud)

为了记录消息:

log_msg "Hello World!";
Run Code Online (Sandbox Code Playgroud)

为了记录我尝试做的另一个函数的stdout:

bgcommand --a --b 2>&1 > log_stream &
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

我在这个问题上找到了记录管道的函数: 管道输出到bash函数 但是缺少了一些东西.

bash logging stdout

1
推荐指数
1
解决办法
868
查看次数

为什么管道输出到bash函数中不起作用

关于此有许多讨论:将输出输出到bash函数

我只想知道为什么:

  #bin/sh
  function myfunc () {
      echo $1
  }

  ls -la | myfunc
Run Code Online (Sandbox Code Playgroud)

将给空行。请问为什么我们的输出ls不被视为$1函数?其背后的机制是什么?

如果我们尝试:

  #bin/sh
  function myfunc () {
      i=${*:-$(</dev/stdin)}
      echo $i
  }

  ls -la | myfunc
Run Code Online (Sandbox Code Playgroud)

然后我们有:

total 32 drwxr-xr-x 6 phil staff 204 Sep 11 21:18 . drwx------+ 17 phil staff 578 Sep 10 21:34 .. lrwxr-xr-x 1 phil staff 2 Sep 10 21:35 s1 -> t1 lrwxr-xr-x 1 phil staff 2 Sep 10 21:35 s2 -> t2 lrwxr-xr-x 1 phil …

unix linux bash shell pipe

1
推荐指数
1
解决办法
456
查看次数

标签 统计

bash ×4

linux ×1

logging ×1

pipe ×1

shell ×1

stdout ×1

unix ×1