I have this code:
myecho() {
if [ -z "$1" ]
then
echo "if";
else
echo "else";
fi
}
alias myecho=myecho
callmyecho() {
append="stuff";
myechoResult='myecho'; #`myecho` wont execute here!
echo $myechoResult$append
}
How I can execute myecho inside callmyecho and append a new text to it?
Editing your code as follows:
#!/bin/bash
myecho() {
if [ -z "$1" ]; then
echo "if"
else
echo "else"
fi
}
callmyecho() {
append="stuff"
myechoResult=`myecho`
echo $myechoResult$append
}
# callmyecho
If you want to call callmyecho within the file and have it execute the myecho function within its block, simply uncomment callmyecho by removing '#'.
On the other hand, if you want to call on the callmyecho function from the terminal, then source the file script first as follows:
$ source ./file
Then you can call on any function inside that file script and it will execute.
Related
I want to create shortcut for 'code file' (VS Code) if there's a second argument, or 'clear' if there's none in a single command line, but i don't know how the bash syntax works.
By looking at the mkcd (mkdir & cd) shortcut that i created:
function mkcd {
if [ ! -n "$1" ]; then
echo "Enter a directory name"
elif [ -d $1 ]; then
echo "\`$1' already exists"
else
mkdir $1 && cd $1
fi
}
I tried to do the same, but the error shows 'syntax error near unexpected token `else''
function c {
if $1 then
code $1
else
clear
fi
}
Your syntax error is that if $1 then is missing a semi-colon (e.g. if $1; then) but read on... There are no "shortcut"s in UNIX. There are scripts, functions, and aliases. It looks like you want to create a function named c to call some command named code when an argument is given, some other command named clear otherwise. That'd be:
c() {
if (( $# > 0 )); then
code "$*"
else
clear
fi
}
my script does not appear to be working even though I get an exit status of 0
It worked until I made it a function with the
makedrivetree ()
{
}
syntax.
If remove that and keep everthing between the while and done it works fine.
I have it saved in my ~/bin folder as makedrivetree
Here is the full function:
#!/usr/bin/env bash
# a script to write the contents of a directory in tree form and save it to a .txt file
### CONSTANTS
DATE="$(date +%Y%m%d)"
### FUNCTIONS
makedrivetree ()
{
while [ "${*}" != "" ] ; do
#set $DRIVE as the first arugment sent to script
DRIVE="${1}"
#set $OUTPUT
OUTPUT="/Users/$USER/Desktop/$(basename "${DRIVE}")_contents_"${DATE}".txt"
#run tree
tree -I "*.dpx" --si --du -U -o "${OUTPUT}" "${DRIVE}"
#check $? for errors
if [ "$?" -eq "0" ] ; then
echo 'done. moving to next drive.'
else
echo 'error'
fi
shift
done
}
#call the function(s)
makedrivetree
echo 'makedrivetree exited with status' $?
exit
You are not passing any argument to that function. Check out your first line of code in the function
while [ "${*}" != "" ]
what you did there was testing if any argument was passed to the function. When you called the function ( makederivetree ), you did not pass any argument to it . To summarise everything , when you called your function , while loop never runs , because of the condition you specified.
calling the function with makedrivetree "$#" solved the problem.
(Excellent tips/explanations/answers in the comments, as well)
I am trying to send a string as a return value from a function which is being called by another function in a different file. One sources the other.
The code is, like so:
#####################################################
##filename: conf_abc.menu
#######################################################
#!/bin/bash
source <path>/conf_pqr.menu
function abc () {
var=$(call_pqr)
echo ${var}
}
##Calling function abc
abc
#########################################################
##filename: conf_pqr.menu
########################################################
#!/bin/bash
RET_VAL=""
function get_intf() {
cmd=`some command`
RET_VAL=${cmd}
}
function call_pqr () {
comm=$(array of choices)
for choice in $comm
do
case $choice in
IF)get_intf;
echo "$RET_VAL";;
esac
done
}
I expect to see the choice from the array in "var" of function abc().
But the "echo ${var}" in conf_abc.menu does not print anything.
I run the script by doing:
./conf_abc.menu
What am I doing wrong?
Thanks for the comments. I found that when the return is called from the function, the entire output from echo is captured into the return variable. I then filtered the output using ">&2". I find that I do get the proper return string.
This I found from:
stackoverflow.com/questions/11758368/shell-script-function-return-a-string
I have put in a minimal example here:
##**file: vlan_menu.sh**
#!/bin/bash
source <path>/ifs_menu.sh
function conf_vlan () {
echo "Calling function if_menu" >&2
local output1=$(if_menu);
echo "printing result" >&2
ENET1="${output1}"
echo "ENET1 is= "${ENET1}"" >&2
}
conf_vlan; --> calling the main function
##**file: ifs_menu.sh**
#!/bin/bash
RET_VAL=""
function get_if() {
PI=$1
local var1=$(shell command)
if [ ! -z "${PI}" ]
then
local var2=<do something with var1>
else
local var2=<do something with var1>
fi
local cmd=$(start shell utility)
RET_VAL=${cmd}
}
function if_menu() {
comm=(1 2 3 4 5)
for choice in ${comm}
do
case $choice in
1) echo "IF" >&2;
get_if "";
echo "${RET_VAL}";;
2) echo "SF" >&2;
get_if $1;
echo "${RET_VAL}";;
esac
done
}
After running "vlan_menu.sh" script file, the value of "ENET1" is the same as "RET_VAL" which is what I wanted to see.
-rsmitha.
My question is simple.
I am using some echo/print wrappers instead of simple echo calls in a bigger bash script. Example:
!/bin/bash
function print_common () { echo "$#"; }
function print_inf () { echo "INFO: $(print_common $#)"; }
function print_war () { echo "WARN: $(print_common $#)"; }
function print_err () { echo "ERROR: $(print_common $#)"; }
Generally, it works very well. The below script1.sh:
!/bin/bash
print_err "Whoops!"
generates:
ERROR: Whoops!
However, script2.sh:
!/bin/bash
print_err "*** Whoops!"
generates:
ERROR: script2.sh Whoops!
The expected print result is:
ERROR: *** Whoops!
Thanks for your help!
In your echo/print wrappers, wrap up a variable print_common with single qoutes
Example:
function print_err () { echo "ERROR: '$(print_common $#)'"; }
If you don't wrap it inside quotes it will:
echo *** Whoops
And if you put a star (*) as an arguments to an echo command it will show you a list of every file inside directory where scirpt is executed.
Using quotes will show you what you want.
I have a shell script which conditionally calls a function.
For Example:-
if [ "$choice" = "true" ]
then
process_install
elif [ "$choice" = "false" ]
then
process_exit
fi
process_install()
{
commands...
commands...
}
process_exit()
{
commands...
commands...
}
Please let me know how to accomplish this.
You don't specify which shell (there are many), so I am assuming Bourne Shell, that is I think your script starts with:
#!/bin/sh
Please remember to tag future questions with the shell type, as this will help the community answer your question.
You need to define your functions before you call them. Using ():
process_install()
{
echo "Performing process_install() commands, using arguments [${*}]..."
}
process_exit()
{
echo "Performing process_exit() commands, using arguments [${*}]..."
}
Then you can call your functions, just as if you were calling any command:
if [ "$choice" = "true" ]
then
process_install foo bar
elif [ "$choice" = "false" ]
then
process_exit baz qux
You may also wish to check for invalid choices at this juncture...
else
echo "Invalid choice [${choice}]..."
fi
See it run with three different values of ${choice}.
Good luck!
#!/bin/bash
process_install()
{
commands...
commands...
}
process_exit()
{
commands...
commands...
}
if [ "$choice" = "true" ] then
process_install
else
process_exit
fi
Example of using a function() in bash:
#!/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_exists function
# $f -> store argument passed to the script
is_file_exists(){
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_exists "$1" )
then
echo "File found: $1"
else
echo "File not found: $1"
fi
The functions need to be defined before being used. There is no mechanism is sh to pre-declare functions, but a common technique is to do something like:
main() {
case "$choice" in
true) process_install;;
false) process_exit;;
esac
}
process_install()
{
commands...
commands...
}
process_exit()
{
commands...
commands...
}
main()
Summary:
Define functions before using them.
Once defined, treat them as commands.
Consider this script, called funcdemo:
#!/bin/bash
[ $# = 0 ] && exhort "write nastygram"
exhort(){
echo "Please, please do not forget to $*"
}
[ $# != 0 ] && exhort "write begging letter"
In use:
$ funcdemo
./funcdemo: line 3: exhort: command not found
$ funcdemo 1
Please, please do not forget to write begging letter
$
Note the potential for a missing function to lie undiscovered for a long time (think 'by a customer at the most critical wrong moment'). It only matters whether the function exists when it is executed, the same as it only matters whether any other command exists when you try to execute it. Indeed, until it goes to execute the command, the shell neither knows nor cares whether it is an external command or a function.
You can create another script file separately for the functions and invoke the script file whenever you want to call the function. This will help you to keep your code clean.
Function Definition : Create a new script file
Function Call : Invoke the script file
#!/bin/bash
# functiontest.sh a sample to call the function in the shell script
choice="true"
function process_install
{
commands...
}
function process_exit
{
commands...
}
function main
{
if [[ "$choice" == "true" ]]; then
process_install
elif [[ "$choice" == "false" ]]; then
process_exit
fi
}
main "$#"
it will start from the main function