简体   繁体   中英

creating bash script that runs for every subsequent command

Suppose I created my own bash script with a command called customcmd

I want it so that if I type in customcmd into the terminal, every subsequent commands following it will also execute customcmd

so suppose I do

>customcmd
>param1
>param2
>param3

I want this to be the equivalent of

>customcmd
>customcmd param1
>customcmd param2
>customcmd param3

ie. I want it to be so that by executing customcmd once, I won't have to type in customcmd again and I want to have the command line parse every single command I type afterwards to automatically be parameters to customcmd...

how do I go about achieving this when writing the bash script?

If I understand your question correctly, I'd do the following:

Create a script, eg mycommand.sh:

#!/bin/bash

while [[ 1 ]]; do

  read _INPUT   
  echo $_INPUT

done
  1. initialize an infinite loop
  2. for each iteration, get the user input ( whatever it is ) and run it through the command you specify in the while loop ( if your script needs to parse multiple arguments, you can swap our echo with a function that can handle that )

Hope that helps!

This could be one of your forms.

#!/bin/bash

shopt -s extglob

function customcmd {
    # Do something with "$@".
    echo "$*"
}

while read -er INPUT -p ">" && [[ $INPUT != *([[:blank:]]) ]]; do
    if [[ $INPUT == customcmd ]]; then
        customcmd
        while read -er INPUT -p ">" && [[ $INPUT != *([[:blank:]]) ]]; do
            customcmd "$INPUT"
        done
    fi
done

Or this:

#!/bin/bash

shopt -s extglob

function customcmd {
    if [[ $# -gt 0 ]]; then
        # Do something with "$@".
        echo "$*"
    else
        local INPUT
        while read -er INPUT -p ">" && [[ $INPUT != *([[:blank:]]) ]]; do
            customcmd "$INPUT"
        done
    fi
}

while read -era INPUT -p ">" && [[ $INPUT != *([[:blank:]]) ]]; do
    case "$INPUT" in
    customcmd)
        customcmd "${INPUT[@]:2}"
        ;;
    # ...
    esac
done

** In arrays $INPUT is equivalent to ${INPUT[0]} , although other people would disagree using the former since it's less "documentive", but every tool has their own traditionally accepted hacks which same people would allow just like those hacks in Awk, and not any Wiki or he who thinks is a more veteran Bash user could dictate which should be standard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM