Shell loop syntax inside makefile if/else - linux

i've loop which I need to add to it if else statment,
if the value ==app1 print x else print y
I've tried with the following
but when I add the else I got syntax error,
what am I doing wrong?
runners:
#for a in $(apps) ; do
if (( a == "app1"));then
echo first: $$v ;
else
echo second: $$v ;
fi
done

I prefer to use bash as my shell, because I'm used to it. Therefore I use SHELL:=/bin/bash at the top of my makefiles. But then your whole makefile fails when a system doesn't provide /bin/bash..
If you want to use the same shell for all the lines in a recipe, you can use the special target .ONESHELL This prevents you from using ;\ after every line with no whitespace behind (error prone). But if you use .ONESHELL then this is true for ALL recipes in your makefile (which I use, but you may not want).
If runners is not a file (and it seems like it, because you do not create a file in the recipe), I would recommend making it .PHONY. Your version might prevent make from executing it, when there happens to be a file named runners while phony targets are always executed.
Double parentheses ((...)) are used for arithmetic expansion. It simply cannot compare strings. Use single or double brackets. See this great post.
I also think you wanted to print a and therefore substituted $$v with $$a.
So in total, this works perfectly fine as long as you have /bin/bash:
SHELL:=/bin/bash
.ONESHELL:
.PHONY: runners
apps:=app2 app3 app1 app5
runners:
#for a in $(apps) ; do <<-- ; between commands as usual
if [[ "$$a" == "app1" ]]; then
echo first: $$a <<-- no need for ; because of .ONESHELL
else
echo second: $$a
fi
done
Output:
second: app2
second: app3
first: app1
second: app5

You use simply the wrong syntax for sh if/else. And you have to add a \ at each end of the command as all that run as a single command in the shell started by make. Attention: No whitespace after \ !
It should be something like:
runners:
#for a in $(apps) ; do \
if [ $$a = "app1" ]; then\
echo first: $$a ; \
else \
echo second: $$a ; \
fi \
done
BTW: Do you really want to print $v? I would expect $a instead ;)

Makefile:
apps=app1 app2
runners:
#for a in $(apps) ; do \
if [ $$a = "app1" ]; then \
echo "first: $$a" ; \
else \
echo "second: $$a" ; \
fi \
done
which prints
first: app1
second: app2

Take care: the solutions above are working in a recent "make" version (probably >4) only.
OSX for example includes Gnu make 3.81. So you would need to install a newer make using Homebrew
brew reinstall make --with-default-names

Related

Passing values to a specific command in a chained command using an alias [duplicate]

I used to use CShell (csh), which lets you make an alias that takes a parameter. The notation was something like
alias junk="mv \\!* ~/.Trash"
In Bash, this does not seem to work. Given that Bash has a multitude of useful features, I would assume that this one has been implemented but I am wondering how.
Bash alias does not directly accept parameters. You will have to create a function.
alias does not accept parameters but a function can be called just like an alias. For example:
myfunction() {
#do things with parameters like $1 such as
mv "$1" "$1.bak"
cp "$2" "$1"
}
myfunction old.conf new.conf #calls `myfunction`
By the way, Bash functions defined in your .bashrc and other files are available as commands within your shell. So for instance you can call the earlier function like this
$ myfunction original.conf my.conf
Refining the answer above, you can get 1-line syntax like you can for aliases, which is more convenient for ad-hoc definitions in a shell or .bashrc files:
bash$ myfunction() { mv "$1" "$1.bak" && cp -i "$2" "$1"; }
bash$ myfunction original.conf my.conf
Don't forget the semi-colon before the closing right-bracket. Similarly, for the actual question:
csh% alias junk="mv \\!* ~/.Trash"
bash$ junk() { mv "$#" ~/.Trash/; }
Or:
bash$ junk() { for item in "$#" ; do echo "Trashing: $item" ; mv "$item" ~/.Trash/; done; }
The question is simply asked wrong. You don't make an alias that takes parameters because alias just adds a second name for something that already exists. The functionality the OP wants is the function command to create a new function. You do not need to alias the function as the function already has a name.
I think you want something like this :
function trash() { mv "$#" ~/.Trash; }
That's it! You can use parameters $1, $2, $3, etc, or just stuff them all with $#
TL;DR: Do this instead
Its far easier and more readable to use a function than an alias to put arguments in the middle of a command.
$ wrap_args() { echo "before $# after"; }
$ wrap_args 1 2 3
before 1 2 3 after
If you read on, you'll learn things that you don't need to know about shell argument processing. Knowledge is dangerous. Just get the outcome you want, before the dark side forever controls your destiny.
Clarification
bash aliases do accept arguments, but only at the end:
$ alias speak=echo
$ speak hello world
hello world
Putting arguments into the middle of command via alias is indeed possible but it gets ugly.
Don't try this at home, kiddies!
If you like circumventing limitations and doing what others say is impossible, here's the recipe. Just don't blame me if your hair gets frazzled and your face ends up covered in soot mad-scientist-style.
The workaround is to pass the arguments that alias accepts only at the end to a wrapper that will insert them in the middle and then execute your command.
Solution 1
If you're really against using a function per se, you can use:
$ alias wrap_args='f(){ echo before "$#" after; unset -f f; }; f'
$ wrap_args x y z
before x y z after
You can replace $# with $1 if you only want the first argument.
Explanation 1
This creates a temporary function f, which is passed the arguments (note that f is called at the very end). The unset -f removes the function definition as the alias is executed so it doesn't hang around afterwards.
Solution 2
You can also use a subshell:
$ alias wrap_args='sh -c '\''echo before "$#" after'\'' _'
Explanation 2
The alias builds a command like:
sh -c 'echo before "$#" after' _
Comments:
The placeholder _ is required, but it could be anything. It gets set to sh's $0, and is required so that the first of the user-given arguments don't get consumed. Demonstration:
sh -c 'echo Consumed: "$0" Printing: "$#"' alcohol drunken babble
Consumed: alcohol Printing: drunken babble
The single-quotes inside single-quotes are required. Here's an example of it not working with double quotes:
$ sh -c "echo Consumed: $0 Printing: $#" alcohol drunken babble
Consumed: -bash Printing:
Here the values of the interactive shell's $0 and $# are replaced into the double quoted before it is passed to sh. Here's proof:
echo "Consumed: $0 Printing: $#"
Consumed: -bash Printing:
The single quotes ensure that these variables are not interpreted by interactive shell, and are passed literally to sh -c.
You could use double-quotes and \$#, but best practice is to quote your arguments (as they may contain spaces), and \"\$#\" looks even uglier, but may help you win an obfuscation contest where frazzled hair is a prerequisite for entry.
All you have to do is make a function inside an alias:
$ alias mkcd='_mkcd(){ mkdir "$1"; cd "$1";}; _mkcd'
^ * ^ ^ ^ ^ ^
You must put double quotes around "$1" because single quotes will not work. This is because clashing the quotes at the places marked with arrows confuses the system. Also, a space at the place marked with a star is needed for the function.
Once I did some fun project and I'm still using it. It's showing some animation while copy files via cp command coz cp don't show anything and it's kind of frustrating. So I've made this alias for cp:
alias cp="~/SCR/spinner cp"
And this is the spinner script
#!/bin/bash
#Set timer
T=$(date +%s)
#Add some color
. ~/SCR/color
#Animation sprites
sprite=( "(* ) ( *)" " (* )( *) " " ( *)(* ) " "( *) (* )" "(* ) ( *)" )
#Print empty line and hide cursor
printf "\n${COF}"
#Exit function
function bye { printf "${CON}"; [ -e /proc/$pid ] && kill -9 $pid; exit; }; trap bye INT
#Run our command and get its pid
"$#" & pid=$!
#Waiting animation
i=0; while [ -e /proc/$pid ]; do sleep 0.1
printf "\r${GRN}Please wait... ${YLW}${sprite[$i]}${DEF}"
((i++)); [[ $i = ${#sprite[#]} ]] && i=0
done
#Print time and exit
T=$(($(date +%s)-$T))
printf "\n\nTime taken: $(date -u -d #${T} +'%T')\n"
bye
It looks like this
Cycled animation)
Here is the link to a color script mentioned above.
And new animation cycle)
So the answer to the OP's question is to use intermediate script that could shuffle args as you wish.
An alternative solution is to use marker, a tool I've created recently that allows you to "bookmark" command templates and easily place cursor at command place-holders:
I found that most of time, I'm using shell functions so I don't have to write frequently used commands again and again in the command-line. The issue of using functions for this use case, is adding new terms to my command vocabulary and having to remember what functions parameters refer to in the real-command. Marker goal is to eliminate that mental burden.
Syntax:
alias shortName="your custom command here"
Example:
alias tlogs='_t_logs() { tail -f ../path/$1/to/project/logs.txt ;}; _t_logs'
Bash alias absolutely does accept parameters. I just added an alias to create a new react app which accepts the app name as a parameter. Here's my process:
Open the bash_profile for editing in nano
nano /.bash_profile
Add your aliases, one per line:
alias gita='git add .'
alias gitc='git commit -m "$#"'
alias gitpom='git push origin master'
alias creact='npx create-react-app "$#"'
note: the "$#" accepts parameters passed in like "creact my-new-app"
Save and exit nano editor
ctrl+o to to write (hit enter); ctrl+x to exit
Tell terminal to use the new aliases in .bash_profile
source /.bash_profile
That's it! You can now use your new aliases
Here's are three examples of functions I have in my ~/.bashrc, that are essentially aliases that accept a parameter:
#Utility required by all below functions.
#https://stackoverflow.com/questions/369758/how-to-trim-whitespace-from-bash-variable#comment21953456_3232433
alias trim="sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*\$//g'"
.
:<<COMMENT
Alias function for recursive deletion, with are-you-sure prompt.
Example:
srf /home/myusername/django_files/rest_tutorial/rest_venv/
Parameter is required, and must be at least one non-whitespace character.
Short description: Stored in SRF_DESC
With the following setting, this is *not* added to the history:
export HISTIGNORE="*rm -r*:srf *"
- https://superuser.com/questions/232885/can-you-share-wisdom-on-using-histignore-in-bash
See:
- y/n prompt: https://stackoverflow.com/a/3232082/2736496
- Alias w/param: https://stackoverflow.com/a/7131683/2736496
COMMENT
#SRF_DESC: For "aliaf" command (with an 'f'). Must end with a newline.
SRF_DESC="srf [path]: Recursive deletion, with y/n prompt\n"
srf() {
#Exit if no parameter is provided (if it's the empty string)
param=$(echo "$1" | trim)
echo "$param"
if [ -z "$param" ] #http://tldp.org/LDP/abs/html/comparison-ops.html
then
echo "Required parameter missing. Cancelled"; return
fi
#Actual line-breaks required in order to expand the variable.
#- https://stackoverflow.com/a/4296147/2736496
read -r -p "About to
sudo rm -rf \"$param\"
Are you sure? [y/N] " response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y)$ ]]
then
sudo rm -rf "$param"
else
echo "Cancelled."
fi
}
.
:<<COMMENT
Delete item from history based on its line number. No prompt.
Short description: Stored in HX_DESC
Examples
hx 112
hx 3
See:
- https://unix.stackexchange.com/questions/57924/how-to-delete-commands-in-history-matching-a-given-string
COMMENT
#HX_DESC: For "aliaf" command (with an 'f'). Must end with a newline.
HX_DESC="hx [linenum]: Delete history item at line number\n"
hx() {
history -d "$1"
}
.
:<<COMMENT
Deletes all lines from the history that match a search string, with a
prompt. The history file is then reloaded into memory.
Short description: Stored in HXF_DESC
Examples
hxf "rm -rf"
hxf ^source
Parameter is required, and must be at least one non-whitespace character.
With the following setting, this is *not* added to the history:
export HISTIGNORE="*hxf *"
- https://superuser.com/questions/232885/can-you-share-wisdom-on-using-histignore-in-bash
See:
- https://unix.stackexchange.com/questions/57924/how-to-delete-commands-in-history-matching-a-given-string
COMMENT
#HXF_DESC: For "aliaf" command (with an 'f'). Must end with a newline.
HXF_DESC="hxf [searchterm]: Delete all history items matching search term, with y/n prompt\n"
hxf() {
#Exit if no parameter is provided (if it's the empty string)
param=$(echo "$1" | trim)
echo "$param"
if [ -z "$param" ] #http://tldp.org/LDP/abs/html/comparison-ops.html
then
echo "Required parameter missing. Cancelled"; return
fi
read -r -p "About to delete all items from history that match \"$param\". Are you sure? [y/N] " response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y)$ ]]
then
#Delete all matched items from the file, and duplicate it to a temp
#location.
grep -v "$param" "$HISTFILE" > /tmp/history
#Clear all items in the current sessions history (in memory). This
#empties out $HISTFILE.
history -c
#Overwrite the actual history file with the temp one.
mv /tmp/history "$HISTFILE"
#Now reload it.
history -r "$HISTFILE" #Alternative: exec bash
else
echo "Cancelled."
fi
}
References:
Trimming whitespace from strings: How to trim whitespace from a Bash variable?
Actual line breaks: https://stackoverflow.com/a/4296147/2736496
Alias w/param: https://stackoverflow.com/a/7131683/2736496 (another answer in this question)
HISTIGNORE: https://superuser.com/questions/232885/can-you-share-wisdom-on-using-histignore-in-bash
Y/N prompt: https://stackoverflow.com/a/3232082/2736496
Delete all matching items from history: https://unix.stackexchange.com/questions/57924/how-to-delete-commands-in-history-matching-a-given-string
Is string null/empty: http://tldp.org/LDP/abs/html/comparison-ops.html
Respectfully to all those saying you can't insert a parameter in the middle of an alias I just tested it and found that it did work.
alias mycommand = "python3 "$1" script.py --folderoutput RESULTS/"
when I then ran mycommand foobar it worked exactly as if I had typed the command out longhand.
NB: In case the idea isn't obvious, it is a bad idea to use aliases for anything but aliases, the first one being the 'function in an alias' and the second one being the 'hard to read redirect/source'. Also, there are flaws (which i thought would be obvious, but just in case you are confused: I do not mean them to actually be used... anywhere!)
I've answered this before, and it has always been like this in the past:
alias foo='__foo() { unset -f $0; echo "arg1 for foo=$1"; }; __foo()'
which is fine and good, unless you are avoiding the use of functions all together. in which case you can take advantage of bash's vast ability to redirect text:
alias bar='cat <<< '\''echo arg1 for bar=$1'\'' | source /dev/stdin'
They are both about the same length give or take a few characters.
The real kicker is the time difference, the top being the 'function method' and the bottom being the 'redirect-source' method. To prove this theory, the timing speaks for itself:
arg1 for foo=FOOVALUE
real 0m0.011s user 0m0.004s sys 0m0.008s # <--time spent in foo
real 0m0.000s user 0m0.000s sys 0m0.000s # <--time spent in bar
arg1 for bar=BARVALUE
ubuntu#localhost /usr/bin# time foo FOOVALUE; time bar BARVALUE
arg1 for foo=FOOVALUE
real 0m0.010s user 0m0.004s sys 0m0.004s
real 0m0.000s user 0m0.000s sys 0m0.000s
arg1 for bar=BARVALUE
ubuntu#localhost /usr/bin# time foo FOOVALUE; time bar BARVALUE
arg1 for foo=FOOVALUE
real 0m0.011s user 0m0.000s sys 0m0.012s
real 0m0.000s user 0m0.000s sys 0m0.000s
arg1 for bar=BARVALUE
ubuntu#localhost /usr/bin# time foo FOOVALUE; time bar BARVALUE
arg1 for foo=FOOVALUE
real 0m0.012s user 0m0.004s sys 0m0.004s
real 0m0.000s user 0m0.000s sys 0m0.000s
arg1 for bar=BARVALUE
ubuntu#localhost /usr/bin# time foo FOOVALUE; time bar BARVALUE
arg1 for foo=FOOVALUE
real 0m0.010s user 0m0.008s sys 0m0.004s
real 0m0.000s user 0m0.000s sys 0m0.000s
arg1 for bar=BARVALUE
This is the bottom part of about 200 results, done at random intervals. It seems that function creation/destruction takes more time than redirection. Hopefully this will help future visitors to this question (didn't want to keep it to myself).
If you're looking for a generic way to apply all params to a function, not just one or two or some other hardcoded amount, you can do that this way:
#!/usr/bin/env bash
# you would want to `source` this file, maybe in your .bash_profile?
function runjar_fn(){
java -jar myjar.jar "$#";
}
alias runjar=runjar_fn;
So in the example above, i pass all parameters from when i run runjar to the alias.
For example, if i did runjar hi there it would end up actually running java -jar myjar.jar hi there. If i did runjar one two three it would run java -jar myjar.jar one two three.
I like this $# - based solution because it works with any number of params.
There are legitimate technical reasons to want a generalized solution to the problem of bash alias not having a mechanism to take a reposition arbitrary arguments. One reason is if the command you wish to execute would be adversely affected by the changes to the environment that result from executing a function. In all other cases, functions should be used.
What recently compelled me to attempt a solution to this is that I wanted to create some abbreviated commands for printing the definitions of variables and functions. So I wrote some functions for that purpose. However, there are certain variables which are (or may be) changed by a function call itself. Among them are:
FUNCNAME
BASH_SOURCE
BASH_LINENO
BASH_ARGC
BASH_ARGV
The basic command I had been using (in a function) to print variable defns. in the form output by the set command was:
sv () { set | grep --color=never -- "^$1=.*"; }
E.g.:
> V=voodoo
sv V
V=voodoo
Problem: This won't print the definitions of the variables mentioned above as they are in the current context, e.g., if in an interactive shell prompt (or not in any function calls), FUNCNAME isn't defined. But my function tells me the wrong information:
> sv FUNCNAME
FUNCNAME=([0]="sv")
One solution I came up with has been mentioned by others in other posts on this topic. For this specific command to print variable defns., and which requires only one argument, I did this:
alias asv='(grep -- "^$(cat -)=.*" <(set)) <<<'
Which gives the correct output (none), and result status (false):
> asv FUNCNAME
> echo $?
1
However, I still felt compelled to find a solution that works for arbitrary numbers of arguments.
A General Solution To Passing Arbitrary Arguments To A Bash Aliased Command:
# (I put this code in a file "alias-arg.sh"):
# cmd [arg1 ...] – an experimental command that optionally takes args,
# which are printed as "cmd(arg1 ...)"
#
# Also sets global variable "CMD_DONE" to "true".
#
cmd () { echo "cmd($#)"; declare -g CMD_DONE=true; }
# Now set up an alias "ac2" that passes to cmd two arguments placed
# after the alias, but passes them to cmd with their order reversed:
#
# ac2 cmd_arg2 cmd_arg1 – calls "cmd" as: "cmd cmd_arg1 cmd_arg2"
#
alias ac2='
# Set up cmd to be execed after f() finishes:
#
trap '\''cmd "${CMD_ARGV[1]}" "${CMD_ARGV[0]}"'\'' SIGUSR1;
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# (^This is the actually execed command^)
#
# f [arg0 arg1 ...] – acquires args and sets up trap to run cmd:
f () {
declare -ag CMD_ARGV=("$#"); # array to give args to cmd
kill -SIGUSR1 $$; # this causes cmd to be run
trap SIGUSR1; # unset the trap for SIGUSR1
unset CMD_ARGV; # clean up env...
unset f; # incl. this function!
};
f' # Finally, exec f, which will receive the args following "ac2".
E.g.:
> . alias-arg.sh
> ac2 one two
cmd(two one)
>
> # Check to see that command run via trap affects this environment:
> asv CMD_DONE
CMD_DONE=true
A nice thing about this solution is that all the special tricks used to handle positional parameters (arguments) to commands will work when composing the trapped command. The only difference is that array syntax must be used.
E.g.,
If you want "$#", use "${CMD_ARGV[#]}".
If you want "$#", use "${#CMD_ARGV[#]}".
Etc.
I will just post my (hopefully, okay) solution
(for future readers, & most vitally; editors).
So - please edit & improve/remove anything in this post.
In the terminal:
$ alias <name_of_your_alias>_$argname="<command> $argname"
and to use it (notice the space after '_':
$<name_of_your_alias>_ $argname
for example, a alias to cat a file called hello.txt:
(alias name is CAT_FILE_)
and the $f (is the $argname, which is a file in this example)
$ alias CAT_FILE_$f="cat $f"
$ echo " " >> hello.txt
$ echo "hello there!" >> hello.txt
$ echo " " >> hello.txt
$ cat hello.txt
hello there!
Test (notice the space after '_'):
CAT_FILE_ hello.txt
As has already been pointed out by others, using a function should be considered best practice.
However, here is another approach, leveraging xargs:
alias junk="xargs -I "{}" -- mv "{}" "~/.Trash" <<< "
Note that this has side effects regarding redirection of streams.
Solution with subcommands:
d () {
if [ $# -eq 0 ] ; then
docker
return 0
fi
CMD=$1
shift
case $CMD in
p)
docker ps --all $#
;;
r)
docker run --interactive --tty $#
;;
rma)
docker container prune
docker image prune --filter "dangling=true"
;;
*)
docker $CMD $#
;;
esac
return $?
}
Using:
$ d r my_image ...
Called:
docker run --interactive --tty my_image ...
Here's the example:
alias gcommit='function _f() { git add -A; git commit -m "$1"; } ; _f'
Very important:
There is a space after { and before }.
There is a ; after each command in sequence. If you forget this after the last command, you will see > prompt instead!
The argument is enclosed in quotes as "$1"
To give specific answer to the Question posed about creating the alias to move the files to Trash folder instead of deleting them:
alias rm="mv "$1" -t ~/.Trash/"
Offcourse you have to create dir ~/.Trash first.
Then just give following command:
$rm <filename>
$rm <dirname>
Here is another approach using read. I am using this for brute search of a file by its name fragment, ignoring the "permission denied" messages.
alias loc0='( IFS= read -r x; find . -iname "*" -print 2>/dev/null | grep $x;) <<<'
A simple example:
$ ( IFS= read -r x; echo "1 $x 2 ";) <<< "a b"
1 a b 2
Note, that this converts the argument as a string into variable(s). One could use several parameters within quotes for this, space separated:
$ ( read -r x0 x1; echo "1 ${x0} 2 ${x1} 3 ";) <<< "a b"
1 a 2 b 3
Functions are indeed almost always the answer as already amply contributed and confirmed by this quote from the man page: "For almost every purpose, aliases are superseded by shell functions."
For completeness and because this can be useful (marginally more lightweight syntax) it could be noted that when the parameter(s) follow the alias, they can still be used (although this wouldn't address the OP's requirement). This is probably easiest to demonstrate with an example:
alias ssh_disc='ssh -O stop'
allows me to type smth like ssh_disc myhost, which gets expanded as expected as: ssh -O stop myhost
This can be useful for commands which take complex arguments (my memory isn't what it use t be anymore...)
For taking parameters, you should use functions!
However $# get interpreted when creating the alias instead of during the execution of the alias and escaping the $ doesn’t work either. How do I solve this problem?
You need to use shell function instead of an alias to get rid of this problem. You can define foo as follows:
function foo() { /path/to/command "$#" ;}
OR
foo() { /path/to/command "$#" ;}
Finally, call your foo() using the following syntax:
foo arg1 arg2 argN
Make sure you add your foo() to ~/.bash_profile or ~/.zshrc file.
In your case, this will work
function trash() { mv $# ~/.Trash; }
Both functions and aliases can use parameters as others have shown here. Additionally, I would like to point out a couple of other aspects:
1. function runs in its own scope, alias shares scope
It may be useful to know this difference in cases you need to hide or expose something. It also suggests that a function is the better choice for encapsulation.
function tfunc(){
GlobalFromFunc="Global From Func" # Function set global variable by default
local FromFunc="onetwothree from func" # Set a local variable
}
alias talias='local LocalFromAlias="Local from Alias"; GlobalFromAlias="Global From Alias" # Cant hide a variable with local here '
# Test variables set by tfunc
tfunc # call tfunc
echo $GlobalFromFunc # This is visible
echo $LocalFromFunc # This is not visible
# Test variables set by talias
# call talias
talias
echo $GlobalFromAlias # This is invisible
echo $LocalFromAlias # This variable is unset and unusable
Output:
bash-3.2$ # Test variables set by tfunc
bash-3.2$ tfunc # call tfunc
bash-3.2$ echo $GlobalFromFunc # This is visible
Global From Func
bash-3.2$ echo $LocalFromFunc # This is not visible
bash-3.2$ # Test variables set by talias
bash-3.2$ # call talias
bash-3.2$ talias
bash: local: can only be used in a function
bash-3.2$ echo $GlobalFromAlias # This is invisible
Global From Alias
bash-3.2$ echo $LocalFromAlias # This variable is unset and unusable
2. wrapper script is a better choice
It has happened to me several times that an alias or function can not be found when logging in via ssh or involving switching usernames or multi-user environment. There are tips and tricks with sourcing dot files, or this interesting one with alias: alias sd='sudo ' lets this subsequent alias alias install='sd apt-get install' work as expect (notice the extra space in sd='sudo '). However, a wrapper script works better than a function or alias in cases like this. The main advantage with a wrapper script is that it is visible/executable for under intended path (i.e. /usr/loca/bin/) where as a function/alias needs to be sourced before it is usable. For example, you put a function in a ~/.bash_profile or ~/.bashrc for bash, but later switch to another shell (i.e. zsh) then the function is not visible anymore.
So, when you are in doubt, a wrapper script is always the most reliable and portable solution.
alias junk="delay-arguments mv _ ~/.Trash"
delay-arguments script:
#!/bin/bash
# Example:
# > delay-arguments echo 1 _ 3 4 2
# 1 2 3 4
# > delay-arguments echo "| o n e" _ "| t h r e e" "| f o u r" "| t w o"
# | o n e | t w o | t h r e e | f o u r
RAW_ARGS=("$#")
ARGS=()
ARG_DELAY_MARKER="_"
SKIPPED_ARGS=0
SKIPPED_ARG_NUM=0
RAW_ARGS_COUNT="$#"
for ARG in "$#"; do
#echo $ARG
if [[ "$ARG" == "$ARG_DELAY_MARKER" ]]; then
SKIPPED_ARGS=$((SKIPPED_ARGS+1))
fi
done
for ((I=0; I<$RAW_ARGS_COUNT-$SKIPPED_ARGS; I++)); do
ARG="${RAW_ARGS[$I]}"
if [[ "$ARG" == "$ARG_DELAY_MARKER" ]]; then
MOVE_SOURCE_ARG_NUM=$(($RAW_ARGS_COUNT-$SKIPPED_ARGS+$SKIPPED_ARG_NUM))
MOVING_ARG="${RAW_ARGS[$MOVE_SOURCE_ARG_NUM]}"
if [[ "$MOVING_ARG" == "$ARG_DELAY_MARKER" ]]; then
echo "Error: Not enough arguments!"
exit 1;
fi
#echo "Moving arg: $MOVING_ARG"
ARGS+=("$MOVING_ARG")
SKIPPED_ARG_NUM=$(($SKIPPED_ARG_NUM+1))
else
ARGS+=("$ARG")
fi
done
#for ARG in "${ARGS[#]}"; do
#echo "ARGN: $ARG"
#done
#echo "RAW_ARGS_COUNT: $RAW_ARGS_COUNT"
#echo "SKIPPED_ARGS: $SKIPPED_ARGS"
#echo "${ARGS[#]}"
QUOTED_ARGS=$(printf ' %q' "${ARGS[#]}")
eval "${QUOTED_ARGS[#]}"

Creating permanent-alias bash command

I am trying to create a "permalias" bash command to be able to easily create permanent aliases without having to directly work on the ~/.bashrc file.
As of now, the only way I've been able to make this work is with this code:
alias permalias="echo alias $1 >> ~/.bashrc"
which allows for an input in this format:
permalias commandname=\"commandbody\"
But I am not satisfied with this because I'd like to mantain a simpler input format, one closer to the original alias command's.
I tried several variants of this code:
alias permalias="echo alias $1=\"$2\" >> ~/.bashrc"
Using this version, this code permalias c "echo test" should add this line alias permalias c="echo test" to the ~/.bashrc file.
But instead this is the result: alias c "echo test", which, of course, does not work.
I'd also be grateful for any advice on how to avoid the need of putting the " around the new command's body.
Thank you
Try this:
#!/bin/bash
permalias()
{
local alias_regex='[A-Za-z_0-9]*'
if
[[ $# = 1 && $1 =~ ($alias_regex)=(.*) ]]
then
printf "%s\n" "${BASH_REMATCH[1]}=\"${BASH_REMATCH[2]}\"" >> ~/.bashrc
else
echo "USAGE: permalias VARNAME=ALIAS_COMMAND"
return 1
fi
}
A nicer version would check for the presence of said alias in .bashrc first, and would then replace it or fail if it is already present.
You can't use arguments in an alias. What you need is a function, something like:
permalias() {
echo "alias ${1}=\"${2}\"" >> ~/.bashrc
}
Make it a function as Olli says, then you could use "$*" to concatenate all the arguments to the function.
permalias() {
n=$1;
shift;
echo "alias $n=\"$*\"" >> ~/.bashrc;
}
This should work with stuff like permalias c echo foo bar, but if you actually want quotes inside the alias, it will get hairy. permalias c echo "foo bar" would not work, you'd need something like permalias c echo "'foo bar'" to counter the additional level of command line processing and get the inside quotes to the file.
For anything complicated, it's better to make a shell function anyway. You can use declare -fp funcname to print the definition of a function, and save it to a file if you like.
If you happen to use zsh, drawing on Fred's answer, we can switch $BASH-REMATCH for $match and send the aliases to .zsh_aliases (assuming you have them set up-- if not add .zsh_aliases to your homedir and add this to your .zshrc: source ~/.zsh_aliases).
So, as an example, I added this function to my .zsh_aliases file and it works well.
permalias() {
sauce="unhash -ma "*" ; unhash -mf "*"; source ~/.zshrc"
local alias_regex='[A-Za-z_0-9]*'
if
[[ $# == 1 && $1 =~ ($alias_regex)=(.*) ]]
then
printf "%s\n" "alias ${match[1]}=\"${match[2]}\"" >>~/.zsh_aliases
#uncomment the following line to automatically load your new alias
#eval ${sauce}
else
echo "Usage: permalias ALIAS_NAME=ALIAS_COMMAND"
return 1
fi
}

linux terminal execute echo function

when I read the book linux shell scripting cookbook
they say when you wanna print !,you shouldn't put it in double quote,or you can add \ before ! to escape it.
e.g.
$echo "Hello,world!"
bash: !:event not found error
$echo "Hello,world\\!"
Hello,world!
but in my situation(ubuntu14.04), I get the answer like that:
$echo "Hello,world!"
Hello,world!
$echo "Hello,world\\!"
Hello,world\!
So, why in my machine can't get the same answer?
Why the escape symbol \ was printed as a normal symbol?
When you're typing interactively to the shell, ! has special meaning, it's the history expansion character. To prevent this special meaning, you need to put it in single quotes or escape it.
echo 'Hello, world!'
echo "Hello, world\!'
The reason it's not happening on Ubuntu may be because it's running a newer version of bash, which is apparently more selective about when history expansion occurs. It seems to require ! to be followed by alphanumerics, not punctuation.
You don't need to do this in scripts, because history is not normally enabled there. It's just for interactive shells.
Create a shell script called file.sh:
#!/bin/bash
# file.sh: a sample shell script to demonstrate the concept of Bash shell functions
# define usage function
usage(){
echo "Usage: $0 filename"
exit 1
}
# define is_file_exits function
# $f -> store argument passed to the script
is_file_exits(){
local f="$1"
[[ -f "$f" ]] && return 0 || return 1
}
# invoke usage
# call usage() function if filename not supplied
[[ $# -eq 0 ]] && usage
# Invoke is_file_exits
if ( is_file_exits "$1" )
then
echo "File found"
else
echo "File not found"
fi
Run it as follows:
chmod +x file.sh
./file.sh
./file.sh /etc/resolv.conf

Execute Command From String Dash Linux

So i am trying to learn how to write scripts for Linux OS's so I wrote this download and install script. Although, I know that any good coder for linux would think this is absolute skid work, It works up to par so far so I just have one error at the moment.
CODE:
#!/bin/sh
###################################
#Lystics Core Linux Code v1 #
# #
# Starting Date 4/14 #
# #
# Ending Date ~ #
# #
###################################
clear
#Define Veriables
dir='./LysticsCode/'
url='http://lysticscode.host-elite.com/Linux/Bash%20Scripts/LCode.sh'
file=$(basename "$url")
echo LysticsCode for Linux v1 Installer
echo
read -r -p "Are you sure you wish to install? [Y/n] " a
if [ "$a" = 'n' -o "$a" = 'N' ]; then
#Not going to install
echo 'Exiting The Installation. Thank You! =D'
exit 1;
else
#Set up screen
clear
echo LysticsCode for Linux v1
echo First Installation
echo ''
#Installing
echo Downloading Packages...
curl -o "$dir$file" "$url"
echo ''
echo ''
echo 'Download Complete!'
eval "alias lcode=/root/LysticsCode/Main.sh"
exit 1;
fi
#End Script
$SHELL
What I am trying to do is add a command alias that will allow the installed files to be accessed much easier. I tried using eval "alias lcode=DIR" and it did not work. Same with $(alias lcode=dir)
Can anyone Help?
alias doesn't inherit to child process. You should not invoke a child shell at the end of the script, instead, say save your script to a file named myenv.sh, execute you script in current shell as:
. myenv.sh
$source /root/LysticsCode/Main.sh
Will work.

gnu make - determine if stdout is terminal

Trying to do:
help:
#echo "you must $(call red_text,clean)"
where red_text is defined as
red_text = $(shell tput setaf 1; echo -n "$1"; tput sgr0)
This prints "you must clean", where word "clean" is printed in red.
The problem is when the output of make is piped (e.g. to less).
In this case I should not use colors, but rather print the $1.
I need to update red_text to handle the case. For that I thought I can use something like $(shell [ -t 1 ] ..) but the problem is that the stdout of $(shell) is never a terminal.
How can I change red to handle the case when stdout is not to a terminal?
As you pointed out, there is no way to test from $(shell ...) whether the output is a standard terminal or a pipe / file. There are however a few things we can do, each with their own pros/cons.
Detect TTY in a custom make script
We simply write a simple shell script that intercepts the call to the native make, detects the TTY, and defines a variable appropriately. The main advantages of this solution:
simplicity,
works for echo, $(info ...) and alike, $(shell ...) commands,
no modification required in the recipes,
no extra process spawned at each echo, which on some platform can be quite slow (eg. Cygwin).
ifdef IS_TTY
# DO NOT ADD TRAILING COMMENTS OR THIS WILL FAIL BECAUSE OF TRAILING SPACES
ESC := $(shell printf '\e')
R := $(ESC)[31m
Z := $(ESC)[0;0m
endif
$(info [info ] $Rred$Z black)
$(shell echo >&2 "[shell ] $Rred$Z black")
if_fancy:
#echo "[recipe] $Rred$Z black"
Example of custom make script to add in path (eg. /usr/local/bin/make):
#! /bin/bash
[ -t 1 ] && IS_TTY=1 || IS_TTY=0
exec /usr/bin/make IS_TTY=$IS_TTY "$#"
This method provides the expected output in all these cases
make # Colored
make >&2 # Colored
make | cat # NOT colored
make >tmp && cat tmp # NOT colored
Detect in recipe and call the Makefile recursively
In some cases, it might not be possible to intercept the call to make or replace it with a custom script. In this solution, we fix that limitation by detecting the TTY in a first pass, and then calling the same Makefile recursively with the appropriate variable set.
ifndef IS_TTY
.SILENT:
%:
#[ -t 1 ] && IS_TTY=1 || IS_TTY=0; $(MAKE) IS_TTY=$$IS_TTY "$#"
xyz:
#[ -t 1 ] && IS_TTY=1 || IS_TTY=0; $(MAKE) IS_TTY=$$IS_TTY
else
ifeq ($(IS_TTY),1)
# DO NOT ADD TRAILING COMMENTS OR THIS WILL FAIL BECAUSE OF TRAILING SPACES
ESC := $(shell printf '\e')
R := $(ESC)[31m
Z := $(ESC)[0;0m
endif
$(info [info ] $Rred$Z black)
$(shell echo >&2 "[shell ] $Rred$Z black")
recursive:
#echo "[recipe] $Rred$Z black"
endif
The disadvantage of this method is that it adds quite some garbage in the Makefile. Dealing with recursion may be tricky. In the example above, I only applied some basic recursive mechanism that should work when make is called with or without a target, and which should also propagate variables. Extending this would be the subject of another question ;-)
Strip the escape sequences at each echo
We test at each echo command whether the output is a TTY, and we strip the escape sequences if not so (using https://superuser.com/questions/380772/removing-ansi-color-codes-from-text-stream). To reduce the spam on the line, we use a make variable $(STRIPESC). The solution is quite simple, but it only works for echo command, and spawns an extra process at each echo. It also requires to edit every recipe with an echo.
# DO NOT ADD TRAILING COMMENTS OR THIS WILL FAIL BECAUSE OF TRAILING SPACES
ESC := $(shell printf '\e')
R := $(ESC)[31m
Z := $(ESC)[0;0m
STRIPESC:=( [ -t 1 ] && cat || sed 's/\x1b\[[0-9;]*m//g' )
# $(info ...) not supported
# $(shell echo >&2 ...) not supported
if_tty:
#echo "[recipe] $Rred$Z black" | $(STRIPESC)
Use an external echo command to strip escape sequences
This is similar to the solution above except that the syntax is a bit more lightweight. The pros/cons are the same. Also, in the example below, I generate the external echo in the makefile itself. In a standard build, you would provide this command as an external tool in some standard path.
# DO NOT ADD TRAILING COMMENTS OR THIS WILL FAIL BECAUSE OF TRAILING SPACES
ESC := $(shell printf '\e')
R := $(ESC)[31m
Z := $(ESC)[0;0m
$(shell echo "#! /bin/bash" > echotty)
$(shell echo '[ -t 1 ] && echo "$$#" || echo "$$#" | sed "s/\x1b\[[0-9;]*m//g"' >> echotty)
$(shell chmod a+x echotty)
# $(info ...)
# $(shell echo >&2 ...)
.PHONY: echotty
echotty:
#./echotty "[recipe] $Rred$Z black"
#fuujuhi already provided a good answer if you care about reliability, but all of his solutions are quite complex. If you need a quick 'n dirty solution, I found this to work quite reliably (although it depends on the implementation of make):
red_text = $(shell [ -c /proc/$$PPID/fd/1 ] && (tput setaf 1; echo -n "$1"; tput sgr0) || echo -n "$1")
Just be aware that it may still detect a tty if you pipe into a character device like /dev/null. This may not be an issue for color output, but in other cases it could be.
if test -t 1
then
echo terminal
else
echo file
fi
In the spirit of Perfection is reached not when there is nothing more to add, but when there is nothing left to take away (Antoine de Saint Exupery), solve the problem by not using color in the first place! Really. It sucks has inherent problems. You make assumptions about terminals that will be wrong for some poor user some fine day. You run into this interactive terminal issue. You spend time solving a problem that could be better spent programming cool functionality instead of eye candy. You please the wrong group of people, namely, the chromatically addicted, and disregard the chromatically challenged, like red/green blind users (of which there are more than you and I estimate).

Resources