Accessing shell variable in a Perl program - linux

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

Related

Multiple files rename using linux shell script

I have following images.
10.jpg
11.jpg
12.jpg
I want to remove above images. I used following shell script file.
for file in /home/scrapping/imgs/*
do
COUNT=$(expr $COUNT + 1)
STRING="/home/scrapping/imgs/""Img_"$COUNT".jpg"
echo $STRING
mv "$file" "$STRING"
done
So, replaced file name
Img_1.jpg
Img_2.jpg
Img_3.jpg
But, I want to replace the file name like this:
Img_10.jpg
Img_11.jpg
Img_12.jpg
So, How to set COUNT value 10 to get my own output?
The expr syntax is pretty outdated, POSIX shell allows you to do arithmetic evaluation with $(()) syntax. You can just do
#!/usr/bin/env bash
count=10
for file in /home/scrapping/imgs/*; do
[ -f "$file" ] || continue
mv "$file" "/home/scrapping/imgs/Img_$((count++)).jpg"
done
Also from the errors reported in the comments, you seem to be running it from the dash shell. It does not seem to have all the features complying to the standard POSIX shell. Run it with the sh or the bash shell.
And always use lowercase letters for user defined variables in your shell script. Upper case letters are primarily for the environment variables managed by the shell itself.
With rename command you can suffix your files with Img_:
rename 's/^/Img_/' *
The ^ means replace the start of the filename with Img_, i.e: adds a suffix.

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

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

Embedded Perl script in Linux shell [duplicate]

This question already has an answer here:
perl inside bash: How to call perl on a script saved in a string
(1 answer)
Closed 7 years ago.
Can I invoke Perl script from Unix shell? For example I have bash script in form like:
#!/bin/sh
echo This is bash
i=12
echo $i
perl <<__HERE__
print "This is perl\n";
my \$i = $i;
print ++\$i . "\n";
echo This is bash again
echo $i
Above is just an example.
Is it possible to pass variables from bash to script? Hope I expressed myself correctly and properly. I need to call Perl script which will take values from bash script and use them and then return processed results.
The problem is the dollar signs need escaped. It makes for an ugly, error prone Perl script. Use environmental variables.
#!/bin/bash
export i=12
readarray results < <(perl <<-'__HERE__'
my $i = $ENV{'i'};
print "$i\n";
$i += 1;
print "$i\n";
__HERE__
)
for r in "${results[#]}"; do echo $r; done
The quotes around HERE prevents bash from doing variable substitution. The "-" allows the here is document to be indented it tabs.
While this is a nice exercise in the finer points of Bash, why not just code in Perl or Bash alone? Bash does regular expressions, arrays, etc. And Perl can do everything Bash can.
This is a way to call a Perl script in Shell script. Make sure Perl script is executable and the first line is #!/usr/bin/perl.
#!/bin/sh
/path/to/perlscript/scriptName.pl arg1 arg2
arg1 arg2 .. are the arguments if you need to pass any.
You can set the PATH and call the script like this:
#!/bin/sh
PATH=/path/to/perlscript/
${PATH}test.pl

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[#]}";

Extract all variable values in a shell script

I'm debugging an old shell script; I want to check the values of all the variables used, it's a huge ugly script with approx more than 140 variables used. Is there anyway I can extract the variable names from the script and put them in a convenient pattern like:
#!/bin/sh
if [ ${BLAH} ....
.....
rm -rf ${JUNK}.....
to
echo ${BLAH}
echo ${JUNK}
...
Try running your script as follows:
bash -x ./script.bash
Or enable the setting in the script:
set -x
You can dump all interested variables in one command using:
set | grep -w -e BLAH -e JUNK
To dump all the variables to stdout use:
set
or
env
from inside your script.
You can extract a (sub)list of the variables declared in your script using grep:
grep -Po "([a-z][a-zA-Z0-9_]+)(?==\")" ./script.bash | sort -u
Disclaimer: why "sublist"?
The expression given will match string followed by an egal sign (=) and a double quote ("). So if you don't use syntax such as myvar="my-value" it won't work.
But you got the idea.
grep Options
-P --perl-regexp: Interpret PATTERN as a Perl regular expression (PCRE, see below) (experimental) ;
-o --only-matching: Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
Pattern
I'm using a positive lookahead: (?==\") to require an egal sign followed by a double quote.
In bash, but not sh, compgen -v will list the names of all variables assigned (compare this to set, which has a great deal of output other than variable names, and thus needs to be parsed).
Thus, if you change the top of the script to #!/bin/bash, you will be able to use compgen -v to generate that list.
That said, the person who advised you use set -x did well. Consider this extension on that:
PS4=':$BASH_SOURCE:$LINENO+'; set -x
This will print the source file and line number before every command (or variable assignment) which is executed, so you will have a log not only of which variables are set, but just where in the source each one was assigned. This makes tracking down where each variable is set far easier.

Resources