Assigning integer values on the command line terminal to be commands - linux

I'm looking for a way of assigning integers to commands to be run. For example when I type '1' within the command line this launches file x. A '2' launches file y etc. Is there any way of doing this?
I'm using Ubuntu 16.04 :) I'm also looking to make these assignments permament.

You can achieve that with alias. For example:
$ alias 1='echo hi'
1
$ 1
echo hi
Add a command you want to be executed after =. In your case it would be something like this:
alias 1='<PATH_TO_FILE>'
To make aliases permanent add them to your ~/.bashrc, or even
better make your setup more modular and add this to your ~/.bashrc:
############################################################
# alias definitions
############################################################
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
And add your alias definitions to ~/.bash_aliases.

Related

Variable containing alias not being expanded correctly

I am trying to automate minikube start process inside WSL2 Debian environment on Windows 10/11.
I have this alias already set inside the .bash_aliases
$ type minikube
minikube is aliased to `"/mnt/c/minikube/minikube.exe"'
and I have this script running on WSL2 start up:
$ cat wsl_minikube_start.sh
shopt -s expand_aliases
alias_location="${HOME}/.bash_aliases"
source "${alias_location}"
ministart="minikube start"
${ministart}
shopt -u expand_aliases
I believe it is supposed to work that way, but it shows the minikube command not found.
$ bash wsl_minikube_start.sh
wsl_minikube_start.sh: line 5: minikube: command not found
(The title was edited to make this easier to find in the future; it was not clear at the time what exactly the problem was.)
Putting a command in a variable is basically always a bad idea, not only because it interferes with alias expansion (basically, aliases are parsed before variable expansions take place). See e.g. https://mywiki.wooledge.org/BashFAQ/050
Aliases are basically always a bad idea, too. Replace your alias with a function instead.
minikube () { "/mnt/c/minikube/minikube.exe" "$#"; }
Or, basically equivalently, create a wrapper script in your PATH with essentially the same contents.
#!/bin/sh
exec "/mnt/c/minikube/minikube.exe" "$#"
Returning to the first topic, it's not clear why you want to encapsulate the simple command minikube start with a variable; but if this really has some purpose, you want to use a function for that, too.
ministart () { minikube start "$#"; }
(The "$#" is only useful if you want to be able to add command-line arguments.)

linux alias to simplify a command line

I am new to writing Linux scripts (in fact I'm not sure if the proper term is Linux script or baSH script). I do understand source-ing and the alias feature such as this:
alias l='ls -ltra'
What I want to accomplish is type the following shortcut statement
php ~/path/to/longProgram.php Argument1 -x -y -z --long-switch long-switch-value
as this:
lp Argument1 -x -y -z --long-switch long-switch-value
i.e. where I can call lp from any where, and where all of the arguments as-given get passed to longProgram.php. How would I do this as an alias?
To make an invocation of lp Argument1 -x -y -z --long-switch long-switch-value result in a call to php ~/path/to/longProgram.php Argument1 -x -y -z --long-switch long-switch-value, you have a few options. The simplest is to put this in your ~/.bashrc:
lp() { php "$HOME/path/to/longProgram.php" "$#"; }
alias lp='php ~/path/to/longProgram.php'
would normally work, even if it is not a good practice. An alias is simply a find and replace feature so I see no reason of this not working. However you need to be the exact user whose home contain the program.
PS: Also verify that lp is not already assigned to another command.
I just found a way to set an alias command and save it for next time.
nano ~/.bashrc or ~/.bash_aliases
add your aliases in this file
Ex:
alias lp='php ~/path/to/longProgram.php
ctrl+x to save the file, then
source ~/.bashrc or ~/.bash_aliases
You will be able to use the alias command everytime you login as the target user.
Note:
If you want to use ~/.bash_aliases, be sure that the ~/.bashrc file has following commands.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
I prefer using bash_aliases to keep your custom alias clean and management in a centrilized file.
Referece:
https://www.cyberciti.biz/faq/create-permanent-bash-alias-linux-unix/

Bash script to go to directory and perform commands gives "Command not found" [duplicate]

This question already has answers here:
How to use aliases defined in .bashrc in other scripts?
(6 answers)
Closed 2 years ago.
My alias defined in a sample shell script is not working. And I am new to Linux Shell Scripting.
Below is the sample shell file
#!/bin/sh
echo "Setting Sample aliases ..."
alias xyz="cd /home/usr/src/xyz"
echo "Setting done ..."
On executing this script, I can see the echo messages. But if I execute the alias command, I see the below error
xyz: command not found
am I missing something ?
source your script, don't execute it like ./foo.sh or sh foo.sh
If you execute your script like that, it is running in sub-shell, not your current.
source foo.sh
would work for you.
You need to set a specific option to do so, expand_aliases:
shopt -s expand_aliases
Example:
# With option
$ cat a
#!/bin/bash
shopt -s expand_aliases
alias a="echo b"
type a
a
$ ./a
# a is aliased to 'echo b'
b
# Without option
$ cat a
#!/bin/bash
alias a="echo b"
type a
a
$ ./a
./a: line 3: type: a: not found
./a: line 4: a: command not found
reference: https://unix.stackexchange.com/a/1498/27031 and https://askubuntu.com/a/98786/127746
sourcing the script source script.sh
./script.sh will be executed in a sub-shell and the changes made apply only the to sub-shell. Once the command terminates, the sub-shell goes and so do the changes.
OR
HACK: Simply run following command on shell and then execute the script.
alias xyz="cd /home/usr/src/xyz"
./script.sh
To unalias use following on shell prompt
unalias xyz
If you execute it in a script, the alias will be over by the time the script finishes executing.
In case you want it to be permanent:
Your alias is well defined, but you have to store it in ~/.bashrc, not in a shell script.
Add it to that file and then source it with . .bashrc - it will load the file so that alias will be possible to use.
In case you want it to be used just in current session:
Just write it in your console prompt.
$ aa
The program 'aa' is currently not installed. ...
$
$ alias aa="echo hello"
$
$ aa
hello
$
Also: From Kent answer we can see that you can also source it by source your_file. In that case you do not need to use a shell script, just a normal file will make it.
You may use the below command.
shopt -s expand_aliases
source ~/.bashrc
eval $command
Your alias has to be in your .profile file not in your script if you are calling it on the prompt.
If you put an alias in your script then you have to call it within your script.
Source the file is the correct answer when trying to run a script that inside has an alias.
source yourscript.sh
Put your alias in a file call ~/.bash_aliases and then, on many distributions, it will get loaded automatically, no need to manually run the source command to load it.

alias in a script

In linux, if I put a command in a script that contains an alias, I see that it doesn't get expanded. How can I fix that? I am using bash.
According the the TLDP page about aliases, you need to use the line shopt -s expand_aliases in your code to expand aliases. The example below produced the expected output, but without the shopt line it just printed "my_ls: command not found":
#!/bin/bash
shopt -s expand_aliases
alias my_ls='ls -lrt'
echo "Trying my_ls"
my_ls
exit
If you want your shell aliases to be available in a script, you must manually include them. If they are defined in ~/.bashrc, put a line
. ~/.bashrc
after the #!/bin/sh line in your script. This will execute the contents of .bashrc in the context of your script.
Enabling posix mode (such as by calling bash as sh or with the command (set -o posix) 2>/dev/null && set -o posix should do the trick.
Even then, be aware that aliases are expanded as they are parsed, and the ordering between parsing and execution is poorly defined. For example
alias foo=echo; foo bar
or
{
alias foo=echo
foo bar
}
will try to run foo as the alias is not defined at parse time yet. Also, some shells parse the whole input of an eval or . (source) before executing any of it.
So the only portable and reliable way to use aliases in scripts is to define them and then eval or . the code that uses them.

How can I define a bash alias as a sequence of multiple commands? [duplicate]

This question already has answers here:
Multiple commands in an alias for bash
(10 answers)
Closed 4 years ago.
I know how to configure aliases in bash, but is there a way to configure an alias for a sequence of commands?
I.e say I want one command to change to a particular directory, then run another command.
In addition, is there a way to setup a command that runs "sudo mycommand", then enters the password? In the MS-DOS days I'd be looking for a .bat file but I'm unsure of the linux (or in this case Mac OSX) equivalent.
For chaining a sequence of commands, try this:
alias x='command1;command2;command3;'
Or you can do this:
alias x='command1 && command2 && command3'
The && makes it only execute subsequent commands if the previous returns successful.
Also for entering passwords interactively, or interfacing with other programs like that, check out expect. (http://expect.nist.gov/)
You mention BAT files so perhaps what you want is to write a shell script. If so then just enter the commands you want line-by-line into a file like so:
command1
command2
and ask bash to execute the file:
bash myscript.sh
If you want to be able to invoke the script directly without typing "bash" then add the following line as the first line of the file:
#! /bin/bash
command1
command2
Then mark the file as executable:
chmod 755 myscript.sh
Now you can run it just like any other executable:
./myscript.sh
Note that unix doesn't really care about file extensions. You can simply name the file "myscript" without the ".sh" extension if you like. It's that special first line that is important. For example, if you want to write your script in the Perl programming language instead of bash the first line would be:
#! /usr/bin/perl
That first line tells your shell what interpreter to invoke to execute your script.
Also, if you now copy your script into one of the directories listed in the $PATH environment variable then you can call it from anywhere by simply typing its file name:
myscript.sh
Even tab-completion works. Which is why I usually include a ~/bin directory in my $PATH so that I can easily install personal scripts. And best of all, once you have a bunch of personal scripts that you are used to having you can easily port them to any new unix machine by copying your personal ~/bin directory.
it's probably easier to define functions for these types of things than aliases, keeps things more readable if you want to do more than a command or two:
In your .bashrc
perform_my_command() {
pushd /some_dir
my_command "$#"
popd
}
Then on the command line you can simply do:
perform_my_command my_parameter my_other_parameter "my quoted parameter"
You could do anything you like in a function, call other functions, etc.
You may want to have a look at the Advanced Bash Scripting Guide for in depth knowledge.
For the alias you can use this:
alias sequence='command1 -args; command2 -args;'
or if the second command must be executed only if the first one succeeds use:
alias sequence='command1 -args && command2 -args'
Your best bet is probably a shell function instead of an alias if the logic becomes more complex or if you need to add parameters (though bash supports aliases parameters).
This function can be defined in your .profile or .bashrc. The subshell is to avoid changing your working directory.
function myfunc {
( cd /tmp; command )
}
then from your command prompt
$ myfunc
For your second question you can just add your command to /etc/sudoers (if you are completely sure of what you are doing)
myuser ALL = NOPASSWD: \
/bin/mycommand
Apropos multiple commands in a single alias, you can use one of the logical operators to combine them. Here's one to switch to a directory and do an ls on it
alias x="cd /tmp && ls -al"
Another option is to use a shell function. These are sh/zsh/bash commands. I don't know enough of other shells to be sure if they work.
As for the sudo thing, if you want that (although I don't think it's a good idea), the right way to go is to alter the /etc/sudoers file to get what you want.
You can embed the function declaration followed by the function in the alias itself, like so:
alias my_alias='f() { do_stuff_with "$#" (arguments)" ...; }; f'
The benefit of this approach over just declaring the function by itself is that you can have a peace of mind that your function is not going to be overriden by some other script you're sourcing (or using .), which might use its own helper under the same name.
E.g., Suppose you have a script init-my-workspace.sh that you're calling like . init-my-workspace.sh or source init-my-workspace.sh whose purpose is to set or export a bunch of environment variables (e.g., JAVA_HOME, PYTHON_PATH etc.). If you happen to have a function my_alias inside there, as well, then you're out of luck as the latest function declaration withing the same shell instance wins.
Conversely, aliases have separate namespace and even in case of name clash, they are looked up first. Therefore, for customization relevant to interactive usage, you should only ever use aliases.
Finally, note that the practice of putting all the aliases in the same place (e.g., ~/.bash_aliases) enables you to easily spot any name clashes.
you can also write a shell function; example for " cd " and "ls " combo here

Resources