Bash command as variable

前端 未结 5 1046
一个人的身影
一个人的身影 2021-01-24 02:43

I am trying to store the start of a sed command inside a variable like this:

sedcmd=\"sed -i \'\' \"

Later I then execute a command like so:

相关标签:
5条回答
  • Why not use an alias or a function? You can do alias as

    alias sedcmd="sed -i '' "
    
    0 讨论(0)
  • 2021-01-24 03:32

    It works when the command is only one word long:

    $ LS=ls
    $ $LS
    

    But in your case, the shell is trying the execute the program sed -i '', which does not exist.

    The workaround is to use $SHELL -c:

    $ $SHELL -c "$LS"
    total 0
    

    (Instead of $SHELL, you could also say bash, but that's not entirely reliable when there are multiple Bash installations, the shell isn't actually Bash, etc.)

    However, in most cases, I'd actually use a shell function:

    sedcmd () {
        sed -i '' "$@"
    }
    
    0 讨论(0)
  • 2021-01-24 03:33

    Define a shell function:

    mysed () {
        sed -i "" "$@"
    }
    

    and call it like this:

    $ mysed s/$orig_pkg/$package_name/g $f
    
    0 讨论(0)
  • 2021-01-24 03:34

    This is the right way for do that

    alias sedcmd="sed -i ''"
    

    Obviously remember that when you close your bash, this alias will be gone.
    If you want to make it "permanent", you have to add it to your .bashrc home file (if you want to make this only for a single user) or .bashrc global file, if you want to make it available for all users

    0 讨论(0)
  • 2021-01-24 03:35

    Not exactly sure what you're trying to do, but my suggestion is:

    sedcmd="sed -i "
    $sedcmd s/$orig_pkg/$package_name/g $f
    

    You must set variables orig_pkg package_name and f in your shell first.

    If you're replacing variable names in a file, try:

    $sedcmd s/\$orig_pkg/\$package_name/g $f
    

    Still f must be set to the file name you're working on.

    0 讨论(0)
提交回复
热议问题