define a shell function without a shell script in bash? [duplicate] - bash

This question already has answers here:
How to define a function on one line
(1 answer)
Define function in unix/linux command line (e.g. BASH)
(5 answers)
Closed 5 years ago.
All I want to do is write and export a shell function without:
1) opening a file
2) editing it
3) saving it
4) running it
I'm aware of the implications... Something like:
$ afunc () { echo "i am awesome" } && export -f afunc
When i call afunc it will print "i am awesome" but if i try to do that I get this situation
$ afunc () { echo "aaa" }
>
Anyway way i can do this dynamically from stdin or something?

This isn't a problem with being inside/outside a script, but a problem in how you're compressing your definition down to a one-liner: You need (but are not including) a semicolon before the closing brace.
The following works:
afunc () { echo "i am awesome"; } && export -f afunc

Related

Unexpected end of file error with every bash script I write [duplicate]

This question already has answers here:
Are shell scripts sensitive to encoding and line endings?
(14 answers)
Closed 3 years ago.
I must be missing something here because no matter what bash compiler I use online and no matter what bash script I write I get the same Unexpected end of file error.
Here's my script
function hello { echo 'hello' } hello
I've also tried this
#!/bin/bash
hello_world () {
echo 'hello, world'
}
jdoodle.sh: line 2: $'\r': command not found
jdoodle.sh: line 3: syntax error near unexpected token `$'{\r''
jdoodle.sh: line 3: `hello_world () {
'
And this
#!/bin/bash
f() { $branchName = "branch" echo $branchName}; f
hello_world
I'm using this tool:
https://www.jdoodle.com/test-bash-shell-script-online/
Why can't I write a simple bash script?
you are missing a ; after your echo command. i just ran this on git bash, recieved the same error then looked at some documentation. After adding the semicolon it functioned perfectly.
function hello { echo 'Hello World!'; }
hello

How can I save the result of a function in a variable in BASH? [duplicate]

This question already has answers here:
Return value in a Bash function
(11 answers)
Closed 4 years ago.
it's my first question. I just want to know how could I save the result of the function 'square' into the variable 'sqr':
!/bin/bash
function square()
{
let y=$x*$x
return $y
}
x=3
**sqr=square**
echo "The square of $x is $sqr"
The functions in bash are really procedures (it does not return anything). Therefore you have two options: Save in a goblal variable the result, or save the output:
function myfunc(){
myresult='anything'
}
myfunc
echo $myresult
or
function myfunc(){
local myresult='anything'
echo "$myresult"
}
result=$(myfunc)
echo $result

How to install a bash function containing variables using a bash script? [duplicate]

This question already has answers here:
How to avoid heredoc expanding variables? [duplicate]
(2 answers)
Closed 6 years ago.
I am attempting to create a bash script that will allow me to install the same bash function across multiple machines. This particular function creates a copy of a file with a timestamp in a backup directory:
filebackup () { cp "${#}" ~/"filebackup/${#}_$(date +%Y-%m-%d_%H:%M:%S).bk"; }
Here is my bash script:
cat <<EOT >> ~/.bashrc
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# create a file backup in ~/filebackup/ with timestamp
filebackup () { cp "${#}" ~/"filebackup/${#}_$(date +%Y-%m-%d_%H:%M:%S).bk"; }
EOT
source ~/.bashrc
When I execute the script, however, the ${#} are missing and the $(date +%Y-%m-%d_%H:%M:%S) has been evaluated. Here is what has been appended to the .bashrc file:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# create a file backup in ~/filebackup/ with timestamp
filebackup () { cp "" ~/"filebackup/_2017-01-05_12:07:56.bk"; }
How can I ensure that the function is copied literally into the file?
A here document is treated as a double-quoted string, so parameter expansions and command substitutions are evaluated before the command reads from them. Quote any part of the delimiter to have the here document treated as a single-quoted string.
cat <<\EOT >> ~/.bashrc
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# create a file backup in ~/filebackup/ with timestamp
filebackup () { cp "${#}" ~/"filebackup/${#}_$(date +%Y-%m-%d_%H:%M:%S).bk"; }
EOT
By any part, I mean any of the following would work just as well:
'EOT'
E\OT
"E"OT
et cetera.
Suggested by #thatotherguy in a comment: quote "EOT" on line 1 (but not on line 6).
cat <<"EOT" >> ~/.bashrc
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# create a file backup in ~/filebackup/ with timestamp
filebackup () { cp "${#}" ~/"filebackup/${#}_$(date +%Y-%m-%d_%H:%M:%S).bk"; }
EOT
source ~/.bashrc

BASH using double variable $ - bad substitution [duplicate]

This question already has answers here:
Bash - variable variables [duplicate]
(4 answers)
Dynamic variable names in Bash
(19 answers)
Closed 5 years ago.
From my code below, how to make the value of 'zz' become 500 after replacing 'critical_' with x on variable 'yy'
xab123=500
yy="critical_ab123"
zz=${"${yy//critical_/x}"}
echo $zz
instead the result, there is an error:
line 8: ${"${yy//critical_/x}"}: bad substitution
thanks
adi
May be like this:
xab123=500
yy="critical_ab123"
zz="${yy//critical_/x}"
echo ${!zz}
500
An interesting usage is when you call a bash function, you can use indirection on the parameters passed in. Then, you can nest calls to your indirection function in a nested manner using command substitution.
deref() { echo "${!1}"; }
aa="bb"
bb="cc"
cc="hello"
echo "$(deref aa)" # bb
echo "$(deref "$(deref aa)")" # cc
echo "$(deref "$(deref "$(deref aa)")")" # hello
Here's deref used to solve the OP's problem:
deref() { echo "${!1}"; }
xab123="500"
yy="critical_ab123"
zz="$(deref "${yy//critical_/x}")"
echo "$zz" # Outputs: 500
Applied edits based on #charles-duffy comments:
Disclaimer: reader beware, there are performance impacts to the command substitution used in this approach (FIFO creation, fork() of a subshell, read() and wait().
Quotes were added to protect against lossy expansion, i.e. echo "$zz" is better than echo $zz
Use POSIX-compliant function declaration syntax, i.e. replaced function deref { echo "${!1}" ; } with deref() { echo "${!1}" ; }
Corrected quoting issue for each quoting context

Command not found on bash function call [duplicate]

This question already has answers here:
Bash script returning "Not found" error
(2 answers)
Closed 9 years ago.
Hi i'm new to bash scripting but cannot understand why i get the command not found error when i try to assign to a local variable the result of this function call with parameters 20120920 5.
#!/bin/bash
function nDaysAgo () #date # daysago
{
date -d "${1} - ${2} days" +%Y%m%d;
}
so the script name is ndaysago, i'm first invoking the script with . ndaysago and then assigning the value like this:
newdate= nDaysAgo 20120910 5
it prints: 20120905: command not found
Meaning that the date execution is made but then tries to use the output as command, thats not what i would expect.
i have also tried assigning the new value to a variable within the function like so:
#!/bin/bash
function nDaysAgo () #date # daysago
{
var=$(date -d "${1} - ${2} days" +%Y%m%d)
}
but still nothing, mmmmmm
Spaces are not allowed around the = when assigning a variable. To invoke a function you should use the $(...) syntax which is called command substitution.
Change to:
newdate=$(nDaysAgo 20120910 5)

Resources