I am writing simple housekeeping script. this script contains following line of codes.This is a sample code i have extracted from the actual code since it is a big file.
#!/bin/bash
ARCHIVE_PATH=/product/file
FunctionA(){
ARCHIVE_USER=user1 # archive storage user name (default)
ARCHIVE_GROUP=group1 # archive storage user group (default)
functionB
}
functionB() {
_name_Project="PROJECT1"
_path_Componet1=/product/company/Componet1/Logs/
_path_Component2=/product/company/Componet2/Logs/
##Component1##
archive "$(_name_Project)" "$(_path_Componet1)" "filename1" "file.log"
}
archive(){
_name= $1
_path=$2
_filename=$3
_ignore_filename=$4
_today=`date + '%Y-%m-%d'`
_archive=${ARCHIVE_PATH}/${_name}_$(hostname)_$(_today).tar
if [ -d $_path];then
echo "it is a directory"
fi
}
FunctionA
When i run the above script , i get the following error
#localhost.localdomain[] $ sh testScript.sh
testScript.sh: line 69: _name_Component1: command not found
testScript.sh: line 69: _path_Component2: command not found
date: extra operand `%Y-%m-%d'
Try `date --help' for more information.
testScript.sh: line 86: _today: command not found
it is a directory
Could someone explain me what am i doing wrong here.
I see the line: _today=date + '%Y-%m-%d'
One error I spotted was resolved by removing the space between the + and the ' like so:
_today=date +'%Y-%m-%d'
I don't see where the _name_Component1 and _name_Component2 variables are declared so can't help there :)
Your variable expansions are incorrect -- you're using $() which is for executing a subshell substitution. You want ${}, i.e.:
archive "${_name_Project}" "${_path_Componet1}" "filename1" "file.log"
As for the date error, no space after the +.
a few things... you are using $(variable) when it should be ${variable}
on the date command, make sure there is no space between the + and the format
and you have name= $1, you don't want that space there
Related
Hi I'm trying to make a function which should get a text file and then do some things on it and then echo. But when I try to execute it, it says syntax error near unexpected token `"$cat"'
#!/bin/usr/bash
cat=$(< cat_dialogue.txt)
function test_cat (){
echo $1
}
test_cat($cat)
desired output:
>meow meow
Your program may look like the following. Note all differences. Check your scripts with shellcheck.
#!/usr/bin/env bash
cat=$(< cat_dialogue.txt)
test_cat() {
echo "$1"
}
test_cat "$cat"
Here is an example BASH function that strips a branchname:
#create function
function strip () {
#create local variable that takes input and fills $TEXT
local TEXT=$1
#stips the branch number from the branchname
echo $TEXT | sed 's/-[0-9]*//2'
}
strip "testbranch-12345-28796"
hope it helps :) also check the BASH documentation as mentioned by #joshmeranda
I'm doing some basic unit testing with the shunit2 unit test framework.
I'm getting the error " syntax error near unexpected token `nodeError=$( node "node_fake_returns/return_error.js" )" on the first line of my function. the function is as follows:
function testHandleNodeReturnError{
nodeError=$( node "./node_fake_returns/return_error.js" )
if [ grep -i "Error" <<< "$nodeError" ]; then
assertTrue "true"
fi
}
It is suppose to run a node script that returns an error message to stdout, then assign that output to a variable. Only this first line in the function is important.
I'm quite new to bash and I've messed with the formatting of this line, mostly just adding spaces in different places, but I can't seem to find what's causing the syntax error. This is probably pretty simple but if somebody could show me what might be wrong I would be greatful.
Thanks!
By pasting your code to shellcheck I was left with:
function testHandleNodeReturnError{
^-- SC1095: You need a space or linefeed between the function name and body.
Which is quite literal. You need a space there.
function testHandleNodeReturnError
Using function keyword is deprecated. Just use function_name() { function_body; }.
if [ grep -i "Error" <<< "$nodeError" ]; then
This is very wrong. This is outputting the content of nodeError variable to standard input of [ command. The [ is a command, a executable, just like grep, it's an alias to test program. Then it runs [ comamnd with grep, -i, "Error" and ] as 4 of it's arguments. You don't want that. If you want to check for Error string, just use grep's exit status:
So do:
testHandleNodeReturnError() {
nodeError=$(node "./node_fake_returns/return_error.js")
if grep -q -i "Error" <<<"$nodeError"; then
assertTrue "true"
fi
}
As I'm new to Unix, can someone help why I get this error?
Error: 0403-057 Syntax error at line 1 : `(' is not expected
Unix server used: AIX servname 1 6 00F635064C00
Script used (to send email alert if day before yesterday source files didn't arrive):
#!/usr/bin/ksh
count=$(sqlplus $PROD_DB #select count(*) from file_audit where (file_name like '%abc%' or file_name like '%dce%') and substr(file_name,17,8)=to_char(to_date(sysdate-2,'DD/MM/YY'), 'yyyymmdd') > asa_file_count.log)
daybefore=`TZ=aaa48 date +%d-%m-%Y`
if [[ $count -lt 20 ]]
then
echo "Alert - Source files are yet to be received for date: $daybefore" | mail -s "Alert : Source data files missing" s#g.com
fi
Parentheses are special to the shell. Your SQL script contains parentheses you don't want the shell to process. However, the shell processes all non-quoted parentheses. Therefore, you can use quotes to prevent the parentheses in your SQL from being interpreted by the shell:
count=$(sqlplus $PROD_DB "#select count(*) from file_audit where (file_name like '%abc%' or file_name like '%dce%') and substr(file_name,17,8)=to_char(to_date(sysdate-2,'DD/MM/YY'), 'yyyymmdd')" > asa_file_count.log)
# ^ and similarly, a closing quote at the end, just before ">asa_file..." .
Now, there is a second issue: you have
count=$(sqlplus ... > asa_file_count.log)
However, I think this means count will always be empty, since the count will go into asa_file_count.log and will not be available to be captured with $(). I believe removing the >asa_file_count.log will probably do what you want:
count=$(sqlplus "$PROD_DB" "<your query>")
(I also put double-quotes around $PROD_DB just in case PROD_DB's value contains any spaces.)
I'm new at bash script writing and I have this error. I have looked everywhere to find an answer with no success. What is wrong with this script?
#!/bin/bash
exec >> /Users/k_herriage/bin/post-gererate.out 2>&1
date
set -x
mynewfile="~/bin/convert_tst.txt"
myfile=fopen($mynewfile,'w+' );
#echo $myfile
fwrite($myfile, "testing");
fclose($myfile);
exit (0)
line 7: syntax error near unexpected token `('
line 7:`myfile = fopen ( '~/bin/convert_tst.txt','w' );'
Few points:
Calling a function in bash does not require parens, it is syntactically equivalent to a command:
do_something arg1 arg2 arg3
There is no need to do open-append-close sequence in bash, it is perfectly doable with a single command:
echo "testing" >> $mynewfile; ##
>> means "append", where if it was >, it would mean "overwrite" or "discard content". (Both will create the file if it didn't exist.)
I have a Bash script that builds a string to run as a command
Script:
#! /bin/bash
matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
teamAComm="`pwd`/a.sh"
teamBComm="`pwd`/b.sh"
include="`pwd`/server_official.conf"
serverbin='/usr/local/bin/rcssserver'
cd $matchdir
illcommando="$serverbin include='$include' server::team_l_start = '${teamAComm}' server::team_r_start = '${teamBComm}' CSVSaver::save='true' CSVSaver::filename = 'out.csv'"
echo "running: $illcommando"
# $illcommando > server-output.log 2> server-error.log
$illcommando
which does not seem to supply the arguments correctly to the $serverbin.
Script output:
running: /usr/local/bin/rcssserver include='/home/joao/robocup/runner_workdir/server_official.conf' server::team_l_start = '/home/joao/robocup/runner_workdir/a.sh' server::team_r_start = '/home/joao/robocup/runner_workdir/b.sh' CSVSaver::save='true' CSVSaver::filename = 'out.csv'
rcssserver-14.0.1
Copyright (C) 1995, 1996, 1997, 1998, 1999 Electrotechnical Laboratory.
2000 - 2009 RoboCup Soccer Simulator Maintenance Group.
Usage: /usr/local/bin/rcssserver [[-[-]]namespace::option=value]
[[-[-]][namespace::]help]
[[-[-]]include=file]
Options:
help
display generic help
include=file
parse the specified configuration file. Configuration files
have the same format as the command line options. The
configuration file specified will be parsed before all
subsequent options.
server::help
display detailed help for the "server" module
player::help
display detailed help for the "player" module
CSVSaver::help
display detailed help for the "CSVSaver" module
CSVSaver Options:
CSVSaver::save=<on|off|true|false|1|0|>
If save is on/true, then the saver will attempt to save the
results to the database. Otherwise it will do nothing.
current value: false
CSVSaver::filename='<STRING>'
The file to save the results to. If this file does not
exist it will be created. If the file does exist, the results
will be appended to the end.
current value: 'out.csv'
if I just paste the command /usr/local/bin/rcssserver include='/home/joao/robocup/runner_workdir/server_official.conf' server::team_l_start = '/home/joao/robocup/runner_workdir/a.sh' server::team_r_start = '/home/joao/robocup/runner_workdir/b.sh' CSVSaver::save='true' CSVSaver::filename = 'out.csv' (in the output after "runnning: ") it works fine.
You can use eval to execute a string:
eval $illcommando
your_command_string="..."
output=$(eval "$your_command_string")
echo "$output"
I usually place commands in parentheses $(commandStr), if that doesn't help I find bash debug mode great, run the script as bash -x script
don't put your commands in variables, just run it
matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
PWD=$(pwd)
teamAComm="$PWD/a.sh"
teamBComm="$PWD/b.sh"
include="$PWD/server_official.conf"
serverbin='/usr/local/bin/rcssserver'
cd $matchdir
$serverbin include=$include server::team_l_start = ${teamAComm} server::team_r_start=${teamBComm} CSVSaver::save='true' CSVSaver::filename = 'out.csv'
./me casts raise_dead()
I was looking for something like this, but I also needed to reuse the same string minus two parameters so I ended up with something like:
my_exe ()
{
mysql -sN -e "select $1 from heat.stack where heat.stack.name=\"$2\";"
}
This is something I use to monitor openstack heat stack creation. In this case I expect two conditions, an action 'CREATE' and a status 'COMPLETE' on a stack named "Somestack"
To get those variables I can do something like:
ACTION=$(my_exe action Somestack)
STATUS=$(my_exe status Somestack)
if [[ "$ACTION" == "CREATE" ]] && [[ "$STATUS" == "COMPLETE" ]]
...
Here is my gradle build script that executes strings stored in heredocs:
current_directory=$( realpath "." )
GENERATED=${current_directory}/"GENERATED"
build_gradle=$( realpath build.gradle )
## touch because .gitignore ignores this folder:
touch $GENERATED
COPY_BUILD_FILE=$( cat <<COPY_BUILD_FILE_HEREDOC
cp
$build_gradle
$GENERATED/build.gradle
COPY_BUILD_FILE_HEREDOC
)
$COPY_BUILD_FILE
GRADLE_COMMAND=$( cat <<GRADLE_COMMAND_HEREDOC
gradle run
--build-file
$GENERATED/build.gradle
--gradle-user-home
$GENERATED
--no-daemon
GRADLE_COMMAND_HEREDOC
)
$GRADLE_COMMAND
The lone ")" are kind of ugly. But I have no clue how to fix that asthetic aspect.
To see all commands that are being executed by the script, add the -x flag to your shabang line, and execute the command normally:
#! /bin/bash -x
matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
teamAComm="`pwd`/a.sh"
teamBComm="`pwd`/b.sh"
include="`pwd`/server_official.conf"
serverbin='/usr/local/bin/rcssserver'
cd $matchdir
$serverbin include="$include" server::team_l_start="${teamAComm}" server::team_r_start="${teamBComm}" CSVSaver::save='true' CSVSaver::filename='out.csv'
Then if you sometimes want to ignore the debug output, redirect stderr somewhere.
For me echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}'
was working fine but unable to store output of command into variable.
I had same issue I tried eval but didn't got output.
Here is answer for my problem:
cmd=$(echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}')
echo $cmd
My output is now 20200824