How to call a variable as a path from another script? - linux

Example
Var = '/etc/sysconfig/..'
export Var
bash script1.sh
in another script1
cat $Var
This is my Problem: The variable does not call the file in this path

Do this:
Var='/etc/sysconfig/..'
bash script1.sh "$Var"
Then in script1.sh:
Var=$1
cat "$Var"
The quotes around "$Var" are required to support paths containing spaces.

Your variable assignment is wrong, it should be:
Var='/etc/sysconfig/..'
No spaces around =.
If you want to send in a environment variable for one script only then you can use:
Var='/etc/sysconfig/..' ./my_script.sh
And inside my_script.sh:
printf "%s\n" "$Var"
# Will print /etc/sysconfig/..
If you want to send arguments to my_script.sh do what #JohnZwinck suggested. What I suggested is only to change environment variable and shouldn't be abused to send/receive regular variables to a command.

I think no need to to more thing
script 1
#!/bin/bash
a="/home/example" ### you can do with export command also export a="/home/example"
sctipt2 ## make effective
. script1;
cd $a

Related

Export variable from within while loop

I want to export a variable from within a loop. I was not able to do it. I am not sure what is missing here.
Any suggestion would be great help
var="ahs tcs amq tos"
for i in ${var}
do
${i}_log="/var/tmp/pmp_${i}_log"
#export ${i}_log
done
The idea is right, just use the declare variable to create variables on the fly. Also avoid using un-quoted variable expansion(for i in ${var}) for looping. Use a proper array syntax as
var=("ahs" "tcs" "amq" "tos")
for i in "${var[#]}"; do
declare ${i}_log="/var/tmp/pmp_${i}_log"
export "${i}_log"
done
As a side note for good practice, always specify the interpreter to run your script. It could be #!/bin/bash or #!/bin/sh or best do it by #!/usr/bin/env bash
This works on dash and bash (as long as the i's and the path to interpolate them into are reasonable):
#!/bin/sh
var="a b c d"
for i in $var
do
export "${i}_log=/var/tmp/pmp_${i}_log"
#test
sh -c "echo \$${i}_log"
done
An alternative could be to use a single exported associative array instead of multiple variables:
EDIT: oops, this won't work since arrays can't be exported. :\
var="ahs tcs amq tos"
declare -A logs
for i in ${var}
do
logs[$i]="/var/tmp/pmp_${i}_log"
done
echo ${logs[#]}
#### export logs
Also see Inian's answer for better practices for looping and arrays.
This can be done in one line without a loop
printf '%s\n' {ahs,tcs,amq,tos} | xargs -I {} bash -c 'export {}_log="/var/tmp/pmp_{}_log"; echo {}_log=${{}_log}'
or with a loop
#!/bin/bash
for i in {ahs,tcs,amq,tos}; do
#export
export "${i}_log=/var/tmp/pmp_${i}_log";
#test
bash -c 'echo '"${i}_log"'='"\$${i}_log"; done
done
The reason ${i}_log="/var/tmp/pmp_${i}_log" failed is because ${i}_log is unquoted and the syntax for exporting is export somevar=somedefintion. In order to dynamically generate the variable name, surround the statement in quotes so that it gets interpolated. ie. export "${dynamic}_var=${dynamic}_definition"
see http://wiki.bash-hackers.org/syntax/quoting

How to create a variable value using $ in the runtime in bash

I have a bash as below where i want to use the value of YYY_XXX_SK_REGISTER_CNTL in the echo .
#! /bin/bash
TRADE_TYPE=$1
YYY_XXX_SK_REGISTER_CNTL=YYY_XXX_SK_REGISTER_template.ctl
echo $TRADE_TYPE"_CTNL"
calling the base as below :
./test.sh YYY_XXX_SK_REGISTER
result expecting in echo : YYY_XXX_SK_REGISTER_template.ctl
If you don't mind changing TRADE_TYPE or using a temporary variable then you can use ${!var} expansion:
TRADE_TYPE="hello"
hello_world=1234
TRADE_TYPE="${TRADE_TYPE}_world"
echo ${!TRADE_TYPE}
# will print 1234
First you need to get rid of the typo, CNTL vs CTNL.
This script does what you want
#!/bin/bash
TRADE_TYPE=$1
YYY_XXX_SK_REGISTER_CNTL=YYY_XXX_SK_REGISTER_template.ctl
eval echo "\$${TRADE_TYPE}_CNTL"
There is probably a better solution than resorting to eval. But you will have to explain what your overall goal is.
I think you are expecting something like below code:
#!/bin/bash
TRADE_TYPE=$1
export TRADE_TYPE
variable="$TRADE_TYPE"_template.ctl
echo $variable
Using indirect variable reference:
#! /bin/bash
TRADE_TYPE="${1}_CNTL"
YYY_XXX_SK_REGISTER_CNTL=YYY_XXX_SK_REGISTER_template.ctl
echo "${!TRADE_TYPE}"
When the following is entered at the command line:
./test.sh YYY_XXX_SK_REGISTER
Your result will be:
YYY_XXX_SK_REGISTER_template.ctl

Return variable from node.js to sh script

Is it possible to execute node.js app from .sh script, return some variable and continue the .sh script?
Something like:
#!/bin/sh
SOME_VARIABLE = node app.js
echo ${SOME_VARIABLE}
Firstly, ensure you're using bash, not sh, as there are significant differences in functionality between the two.
One simple solution is command substitution, although be aware that trailing newlines in the command output will be stripped. Also, when echoing, to protect the contents of the variable (such as spaces and glob characters) from metaprocessing by the shell, you have to double-quote it:
#!/bin/bash
output=$(node app.js);
echo "$output";
Another solution is process substitution in more recent versions of bash. You could even collect the output as an array of lines in this case:
#!/bin/bash
exec 3< <(node app.js);
lines=();
while read -r; do lines+=("$REPLY"); done <&3;
exec 3<&-;
echo "${lines[#]}";

Shell - Write variable contents to a file

I would like to copy the contents of a variable (here called var) into a file.
The name of the file is stored in another variable destfile.
I'm having problems doing this. Here's what I've tried:
cp $var $destfile
I've also tried the same thing with the dd command... Obviously the shell thought that $var was referring to a directory and so told me that the directory could not be found.
How do I get around this?
Use the echo command:
var="text to append";
destdir=/some/directory/path/filename
if [ -f "$destdir" ]
then
echo "$var" > "$destdir"
fi
The if tests that $destdir represents a file.
The > appends the text after truncating the file. If you only want to append the text in $var to the file existing contents, then use >> instead:
echo "$var" >> "$destdir"
The cp command is used for copying files (to files), not for writing text to a file.
echo has the problem that if var contains something like -e, it will be interpreted as a flag. Another option is printf, but printf "$var" > "$destdir" will expand any escaped characters in the variable, so if the variable contains backslashes the file contents won't match. However, because printf only interprets backslashes as escapes in the format string, you can use the %s format specifier to store the exact variable contents to the destination file:
printf "%s" "$var" > "$destdir"
None of the answers above work if your variable:
starts with -e
starts with -n
starts with -E
contains a \ followed by an n
should not have an extra newline appended after it
and so they cannot be relied upon for arbitrary string contents.
In bash, you can use "here strings" as:
cat <<< "$var" > "$destdir"
As noted in the comment by Ash below, #Trebawa's answer (formulated in the same room as mine!) using printf is a better approach than cat.
All of the above work, but also have to work around a problem (escapes and special characters) that doesn't need to occur in the first place: Special characters when the variable is expanded by the shell. Just don't do that (variable expansion) in the first place. Use the variable directly, without expansion.
Also, if your variable contains a secret and you want to copy that secret into a file, you might want to not have expansion in the command line as tracing/command echo of the shell commands might reveal the secret. Means, all answers which use $var in the command line may have a potential security risk by exposing the variable contents to tracing and logging of the shell.
For variables that are already exported, use this:
printenv var >file
That means, in case of the OP question:
printenv var >"$destfile"
Note: variable names are case sensitive.
Warning: It is not a good idea to export a variable just for the sake of printing it with printenv. If you have a non-exported script variable that contains a secret, exporting it will expose it to all future child processes (unless unexported, for example using export -n).
If I understood you right, you want to copy $var in a file (if it's a string).
echo $var > $destdir
When you say "copy the contents of a variable", does that variable contain a file name, or does it contain a name of a file?
I'm assuming by your question that $var contains the contents you want to copy into the file:
$ echo "$var" > "$destdir"
This will echo the value of $var into a file called $destdir. Note the quotes. Very important to have "$var" enclosed in quotes. Also for "$destdir" if there's a space in the name. To append it:
$ echo "$var" >> "$destdir"
you may need to edit a conf file in a build process:
echo "db-url-host=$POSTGRESQL_HOST" >> my-service.conf
You can test this solution with running before export POSTGRESQL_HOST="localhost"

Accessing shell variable in a Perl program

I have this Perl script:
#!/usr/bin/perl
$var = `ls -l \$ddd` ;
print $var, "\n";
And ddd is a shell variable
$ echo "$ddd"
arraytest.pl
When I execute the Perl script I get a listing of all files in the directory instead of just one file, whose file name is contained in shell variable $ddd.
Whats happening here ? Note that I am escaping $ddd in backticks in the Perl script.
The variable $ddd isn't set *in the shell that you invoke from your Perl script.
Ordinary shell variables are not inherited by subprocesses. Environment variables are.
If you want this to work, you'll need to do one of the following in your shell before invoking your Perl script:
ddd=arraytest.pl ; export ddd # sh
export ddd=arraytest.pl # bash, ksh, zsh
setenv ddd arraytest.pl # csh, tcsh
This will make the environment variable $ddd visible from your Perl script. But then it probably makes more sense to refer to it as $ENV{ddd}, rather than passing the literal string '$ddd' to the shell and letting it expand it:
$var = `ls -l $ENV{ddd}`;
You forgot to export ddd:
Mark each name to be passed to child processes in the environment.
So ddd is not automatically available to child processes.
The hash %ENV contains your current environment.
$var = `ls -l $ENV{ddd}`;
/edit - it works, checked, of course ddd need to be exported before running script
export ddd='arraytest.pl'
perl script.pl

Resources