Ubuntu – How to create a custom terminal command with a variable argument

bashcommand line

I already read How can I create a custom terminal command (to run a script)?
. But this always executes the same command.

What I want is, for example, instead of having to type

gcc -m32 -g -zexecstack -fno-stack-protector -mpreferred-stack-boundary=2 -no-pie -fno-pic -o program program.c

I'll just have to type a custom command like

custom-gcc program

or at least

custom-gcc -o program program.c

It would also be good if I could add options to the custom command that would also be added to gcc.

How can I do this? Thanks

Best Answer

General answer:
Open your web browser on www.tldp.org and look for the "Bash guides"

Simple answer:
Open a terminal (Shell) and type (in the process you will see text not shown here)

cd
mkdir bin
echo >>.bash_aliases 'PATH=$PATH:$HOME/bin'
cat <<EOF >bin/custom-gcc
#!/bin/bash
gcc -m32 -g -zexecstack -fno-stack-protector \
    -mpreferred-stack-boundary=2 -no-pie -fno-pic \
    -o "$1" "$1.c"
EOF
chmod 755 bin/custom-gcc
exit

Now

  • open an new Terminal (shell),
  • cd into a folder where you have e.g. "program.c" and type
  • custom-gcc program

... this should from now on execute your custom-gcc with the effect you wish.

NOTE: The bash guides behind the link above will provide all the information you need to improve the simple script created by the above instructions.

Explanation:
cd ensures you're in $HOME/

The next two lines creates a bin/ subfolder in your home directory and makes it be a place to look into, to find "commands".

The lines from cat to EOF is a simple way of creating a text file, here the text file content will be a bash script that does what you request (hint: read the Bash guides to understand the content).

The chmod sets "mode-flags" on the just created file, such that it will be consider "executable".

The very last line exits the shell.

As you from now on open a new shell (terminal) the $PATH variable will have your personal "$HOME/bin/" folder, leading to any files there being considered as possible commands to execute - as you type the name of one of them at the shell prompt.