How to add an extra argument conditionally in bash

2020-02-29 18:31发布

There's a script that calls the other program. The following is program.sh. It might look non-sense but I'm omitting lots of details and… Let's say I wanna stick to the structure as is.

#!/usr/bin/env bash
function run_this {
    /usr/bin/foo -A -B -C
}
run_this

I wanna change the arguments passed to /usr/bin/foo by the argument passed to program.sh. So for example, if you call program.sh --quiet then /usr/bin/foo -A -B -C -X. What's the best way to achieve this?

标签: bash shell
2条回答
该账号已被封号
2楼-- · 2020-02-29 18:39

You could add a conditional. I'm sure there are less repetitive ways to do it but this should work:

#!/bin/bash

function run_this {
    if [[ "$1" = "--quiet" ]]; then
       /usr/bin/foo -A -B -C -X
    else 
       /usr/bin/foo -A -B -C
    fi
}
run_this "$1"
查看更多
Rolldiameter
3楼-- · 2020-02-29 18:41

Use an array.

cmd=(/usr/bin/foo -A -B -C)
if somecond; then
  cmd+=(-X)
fi
"${cmd[@]}"
查看更多
登录 后发表回答