【问题标题】:How to store the output of C program using Bash shell scripting如何使用 Bash shell 脚本存储 C 程序的输出
【发布时间】:2020-09-05 02:29:46
【问题描述】:

这是我的 C 程序

int main(){

int n;
while(1){
    printf("Enter n:\n");
    scanf("%d",&n);
    switch(n){
        case 1: int t; 
            scanf("%d",&t);
            if(t<10)
            printf("true");
            else printf("false");
            break;
        case 2: char c;
            scanf("%c",c);
            if(c=='a') printf("true");
            else printf("false");
            break;
        case -1: break;
    }
        if (n==-1) break;   
}

return 0;
}

这是我的 bash shell 脚本

./a.out << 'EOF'
1
4
2
b
-1
EOF

这将执行代码但不保存输出

./a.out > outputfile

上面的代码会保存输出,包括“Enter n”。

我想执行代码并只保存真/假部分(即排除所有其他 printf)。如何存储文件的输出并为其提供输入?

【问题讨论】:

  • 如果你知道输入,避免不必要的 printf,你可以达到你想要的。
  • @SudoPehpeh :您的程序写入标准输出,因此outputfile 将包含所有printf 结果。如果您不想在标准输出中包含所有内容,请将不需要的部分写入标准错误,即fprintf( stderr, "everything you do not want to capture")
  • @AbhijitNathwani 通常该文件应该由用户运行,因此需要打印语句来告诉用户输入什么。 shell 脚本代码只是检查给定的输入,代码是否给出了正确的输入。

标签: c bash shell output sh


【解决方案1】:

我为 a.out 做了一个替代品,可以用于测试。 is_odd.sh 寻找奇数:

#!/bin/bash

exitfalse() {
   echo $*
   echo false
   exit 1
}

exittrue()
{
   echo $*
   echo true
   exit 0
}

[ $# -eq 0 ] && exitfalse I wanted a number
[[ $1 =~ [0-9]+ ]] || exitfalse Only numbers please
(( $1 % 2  == 0 )) && exitfalse Even number
exittrue Odd number

使用这个冗长的脚本会产生很多垃圾

#!/bin/bash
testset() {
   for input in john doe 1 2 3 4; do
      echo "Input ${input}"
      ./is_odd.sh "${input}"
   done
}

testset

如何在一个文件中拥有相同的输出并且只有 false/true? 使用tee将输出发送到屏幕和一些将进行过滤的进程:

testset | tee >(egrep "false|true" > output)

我认为上面的命令最适合您的问题,我希望看到输入字符串:

testset | tee >(egrep "Input|false|true" > output)

【讨论】:

    【解决方案2】:
    ./a.out < input.txt > output.txt
    

    【讨论】:

    • 好的。但是只保存 switch case 的输出呢?
    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2019-08-11
    • 2023-03-11
    • 2012-05-19
    相关资源
    最近更新 更多