Home > OS >  how to extend a command without changing the usage
how to extend a command without changing the usage

Time:12-11

I have a global npm package that provided by a third party to generate a report and send it to server.

in_report generate -date 20221211

And I want to let a group of user to have the ability to check whether the report is generated or not, in order to prevent duplication. Therefore, I want to run a sh script before executing the in_report command.

sh check.sh && in_report generate -date 20221211

But the problem is I don't want to change the command how they generate the report. I can do a patch on their PC (able to change the env path or etc).

Is it possible to run sh check.sh && in_report generate -date 20221211 by running in_report generate -date 20221211?

CodePudding user response:

If this "in_report" is only used for this exact purpose, you can create an alias by putting the following line at the end of the ".bashrc" or ".bash_aliases" file that is used by the people who will need to run in_report :
alias in_report='sh check.sh && in_report'
See https://doc.ubuntu-fr.org/alias for details.

If in_report is to be used in other ways too, this is not the solution. In that case, you may want to call it directly inside check.sh if a certain set of conditions on the parameters are matched. To do that :
alias in_report='sh check.sh'
The content of check.sh :

#!/bin/sh

if [[ $# -eq 3 && "$1" == "generate" && "$2" == "-date" && "$3" == "20"* ]] # Assuming that all you dates must be in the 21st century
then
    if [[ some test to check that the report has not been generated yet ]] 
    then
        /full/path/to/the/actual/in_report "$@" # WARNING : be sure that nobody will move the actual in_report to another path
    else
        echo "This report already exists"
    fi
else
    /full/path/to/the/actual/in_report "$@"
fi

This sure is not ideal but it should work. But by far the easiest and most reliable solution if applicable would be to ignore the aliasing thing and tell those who will use in_report to run your check.sh instead (with the same parameters as they would put to run in_report), and then you can directly call in_report instead of the /full/path/to/the/actual/in_report.

Sorry if this was not very clear. In that case, feel free to ask.

CodePudding user response:

On most modern Linux distros the easiest would be to place a shell script that defines a function in /etc/profile.d, e.g. /etc/profile.d/my_report with a content of

function in_report() { sh check.sh && /path/to/in_report $*; }

That way it gets automatically placed in peoples environment when they log in.

The /path/to is important so the function doesn't call itself recursively.

A cursory glance through doco for the Mac suggests that you may want to edit /etc/bashrc or /etc/zshrc respectively.

  • Related