I am trying to write a script where the user can pass startDate and endDate via arguments when running the script. Here's my script (saved as test.sh)-   VAR="$(curl -f -X POST -H 'X-API-TOKEN: XXXXXX' -H 'Content-Type: application/json' -d '{"format": "csv", "startDate": $1, "endDate": $2}' 'https://xxx.qualtrics.com/export-responses' | sed -E -n 's/.*([^"]+).+/\1/p')" echo $VAR   When running the script I type the following -   ~/test.sh '"2020-05-13T17:11:00Z","2020-05-13T20:32:00Z"'   The script throws an error.
99178
Consider I've set variable site and needs to be printed by echo or printf, but If I use single quote to write something and want to use variable then how?  Example:  $ site=unix.stackexchange.com $ echo "visit:$site" visit:unix.stackexchange.com   But If I use single quote:  $ echo 'visit:$site' visit:$site   Then we know that '' is strong quote and will not expand the variable   I've tried something:  $ echo 'visit:"$site"' visit:"$site"   but do not succeed. So, I am looking for way to print value inside variable while using single quote.
44440
I have a local script that I want to run on several remote servers. The command syntax I'm using is:  ssh &lt;remote_server&gt; "bash -s" &lt; ./local_script.sh   This works fine, and even lets me pass parameters to local_script.sh. However, I'd really like to pass an input file to it, as in:  local_script.sh &lt; local_file.txt   Combining these two statements gives:  ssh &lt;remote_server&gt; "bash -s" &lt; ./local_script.sh &lt; local_file.txt   When I run this, I get  bash: line 1: FOO: command not found bash: line 2: BAR: command not found bash: line 3: BAZ: command not found ...   where FOO, BAR, BAZ, etc. are the first word on each line of local_file.txt:  FOO     FOO_PARAM1 BAR     BAR_PARAM1 BAZ     BAZ_PARAM2 ...   So, it looks like "bash -s" on the remote server is interpreting local_file.txt as a script file, instead of an input file to local_script.sh. Is there any way to fix this (other than creating a wrapper script)?
121409
My script (should) acts differently, depending on the presence of the data in the input stream. So I can invoke it like this:  $ my-script.sh   or:  $ my-script.sh &lt;&lt;-MARK     Data comes...     ...data goes. MARK   or:  $ some-command | my-script.sh   where two last cases should read the data, while first case should notice the data is missing and act accordingly.  The crucial part (excerpt) of the script is:  #!/bin/bash local myData; read -d '' -t 0 myData;  [ -z "${myData}" ] &amp;&amp; {     # Notice the lack of the data. } || {     # Process the data. }   I use read to read input data, then option -d '' to read multiple lines, as this is expected, and the -t 0 to set timeout to zero. Why the timeout? According to  (typing left unchanged; bold is mine):     -t timeout time out and return failure if a complete line of input is               not read withint TIMEOUT seconds.  The value of the TMOUT               variable is the default timeout.  TIMEOUT may be a               fractional number.  If TIMEOUT is 0, read returns success only               if input is available on the specified file descriptor.  The               exit status is greater than 128 if the timeout is exceeded   So I in case 2 and 3 it should read the data immediately, as I understand it. Unfortunately it doesn't. As -t can take fractional values (according to above man page), changing read line to:  read -d '' -t 0.01 myData;   actually reads the data when data is present and skips it (after 10ms timeout) if it is not. But it should also work when TIMEOUT is set to real 0.  Why it actually doesn't? How can this be fixed? And is there, perhaps, alternative solution to the problem of "act differently depending on the presence of the data"?  UPDATE  Thanks to @Isaac I found a misleading discrepancy between quoted on-line version and my local one (normally I do not have locale set to en_US, so help read gave me translation which I couldn't paste here, and looking up for on-line translation was faster than setting new env---but that caused the whole problem).  So for 4.4.12 version of Bash it says:     If TIMEOUT is 0, read returns               immediately, without trying to read any data, returning               success only if input is available on the specified               file descriptor.   This gives a little bit different impression than "If TIMEOUT is 0, read returns success only if input is available on the specified file descriptor"---for me it implied actually an attempt to read the data.  So finally I tested this and it worked perfectly:  read -t 0 &amp;&amp; read -d '' myData;   The meaning: see if there's anything to read and if it succeed, just read it.  So as to base question, the correct answer was provided by Isaac. And as to alternative solution I prefer the above "read &amp;&amp; read" method.
110182
I'm trying to use the following script to generate a sitemap for my website. When I run it as sh thsitemap.sh I get an error like this and creates an empty sitemap.xml file:  thsitemap.sh: 22: thsitemap.sh: [[: not found thsitemap.sh: 42: thsitemap.sh: [[: not found thsitemap.sh: 50: thsitemap.sh: Syntax error: "(" unexpected   But as the same user root when I manually copy and paste these lines on the terminal, it works without any error and the sitemap.xml file have all the urls. What's the problem? How can I fix this?  #!/bin/bash ############################################## # modified version of original http://media-glass.es/ghost-sitemaps/ # for ghost.centminmod.com # http://ghost.centminmod.com/ghost-sitemap-generator/ ############################################## url="techhamlet.com" webroot='/home/leafh8kfns/techhamlet.com' path="${webroot}/sitemap.xml" user='leafh8kfns'       # web server user group='leafh8kfns'      # web server group  debug='n' # disable debug mode with debug='n' ############################################## date=`date +'%FT%k:%M:%S+00:00'` freq="daily" prio="0.5" reject='.rss, .gif, .png, .jpg, .css, .js, .txt, .ico, .eot, .woff, .ttf, .svg, .txt' ############################################## # create sitemap.xml file if it doesn't exist and give it same permissions # as nginx server user/group if [[ ! -f "$path" ]]; then     touch $path     chown ${user}:${group} $path fi  # check for robots.txt defined Sitemap directive # if doesn't exist add one # https://support.google.com/webmasters/answer/183669 if [ -f "${webroot}/robots.txt" ]; then SITEMAPCHECK=$(grep 'Sitemap:' ${webroot}/robots.txt)     if [ -z "$SITEMAPCHECK" ]; then     echo "Sitemap: http://${url}/sitemap.xml" &gt;&gt; ${webroot}/robots.txt     fi fi ############################################## echo "" &gt; $path  # grab list of site urls list=`wget -r --delete-after $url --reject=${reject} 2&gt;&amp;1 |grep "\-\-"  |grep http | grep -v 'normalize\.css' | awk '{ print $3 }'`  if [[ "$debug" = [yY] ]]; then     echo "------------------------------------------------------"     echo "Following list of urls will be submitted to Google"     echo $list     echo "------------------------------------------------------" fi  # put list into an array array=($list)  echo "------------------------------------------------------" echo ${#array[@]} "pages detected for $url"  echo "------------------------------------------------------"  # formatted properly according to # https://support.google.com/webmasters/answer/35738 echo "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt; &lt;urlset xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9  http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"&gt;" &gt; $path  echo '     ' &gt;&gt; $path;    for ((i=0;i&lt;${#array[*]};i++)); do echo "&lt;url&gt;     &lt;loc&gt;${array[$i]:0}&lt;/loc&gt;     &lt;lastmod&gt;$date&lt;/lastmod&gt;     &lt;changefreq&gt;$freq&lt;/changefreq&gt;     &lt;priority&gt;$prio&lt;/priority&gt; &lt;/url&gt;" &gt;&gt; $path    done echo "" &gt;&gt; $path echo "&lt;/urlset&gt;" &gt;&gt; $path  # notify Google # URL encode urls as per https://support.google.com/webmasters/answer/183669 if [[ "$debug" = [nN] ]]; then     wget  -q --delete-after http://www.google.com/webmasters/tools/ping?sitemap=http%3A%2F%2F${url}%2Fsitemap.xml      rm -rf ${url} else     echo "wget  -q --delete-after http://www.google.com/webmasters/tools/ping?sitemap=http%3A%2F%2F${url}%2Fsitemap.xml"      echo "rm -rf ${url}" fi echo "------------------------------------------------------"  exit 0
33452
In a shell script, I'm processing, some addition process will print an output. If it is a single-digit one, then it has to add zero as a prefix. Here is my current script: c_year=2020 for i in {01..11}         do               n_year=2020             echo 'Next Year:'$n_year             if [[ $i == 11 ]]             then n_month=12             echo 'Next Month:'$n_month             else              n_month=$(($i + 1))             echo 'Next Month:'$n_month             fi             echo $date&quot; : Processing data '$c_year-$i-01 00:00:00' and '$n_year-$n_month-01 00:00:00'&quot;         done  The i value is in doule digit, but the n_month is still printing single digit. How do I set default shell output should return as double digit? Or any alternate way to solve this?
104213
What's in my terminal  bash: settings64.csh: line 35: syntax error near unexpected token `(' bash: settings64.csh: line 35: `foreach i ( $xlnxInstLocList )'   Portion of the script  set xlnxInstLocList="${xlnxInstLocList} common" set xlnxInstLocList="${xlnxInstLocList} EDK" set xlnxInstLocList="${xlnxInstLocList} PlanAhead" set xlnxInstLocList="${xlnxInstLocList} ISE" set XIL_SCRIPT_LOC_TMP_UNI=${XIL_SCRIPT_LOC} foreach i ( $xlnxInstLocList )   Location of syntactical error at the bottom  line 35 foreach i ( $xlnxInstLocList )   I'm not a scripter; I'm trying to fix an error in the scripting for my ISE DESIGN SUITE installation. I just need a quick set of code to replace "foreach i ( $xlnxInstLocList )" to perform its intended function. I think it's a Bash script.
56440
I'm running a script that it requests entering 'y' on each operation, I am looking for a solution like $ ./script &lt; echo 'yyyyyyyyyyyyyy' to pass all my inputs in one time.
24174
I'm trying to create an interactive bash script where I can collect user input variables to be used as arguments in another command. Can someone provide me an example of this?  Currently i want to do:   what type of content you want to delete? what is the status?   then feed it into a mysql delete query command.
48283
I am taking the Linux Essentials class and was doing well until I hit the scripting chapter. I simply do not understand these concepts.  Wondering if someone can break the following down into ultra simplistic terms or point me to a better reference to learn it. I'm currently using netacad's curriculum.        From the text book (with minor formatting changes):     There are some special variables in addition to the ones you set. You   can pass arguments to your script:  #!/bin/bash echo "Hello $1"       A dollar sign followed by a number N corresponds to the Nth argument   passed to the script. If you call the example above with ./test.sh the   output will be Hello Linux. The $0 variable contains the name of the   script itself.      After a program runs, be it a binary or a script, it returns an exit   code which is an integer between 0 and 255. You can test this through   the $? variable to see if the previous command completed successfully.     I understand how to assign variables and how they work with the $ but the whole issue with $0 and $1 -- I just don't get it.    Any help would be much appreciated.
84426
I am creating a simple backup script. I would like to have a message saying "You last backed up x days ago" on login. I can create a file when I do the backup "backup/.last_backup_timestamp" but what format should I use and how would I find the difference in days between then and now in bash?  Thank-you
26277
I run the following line from my bash script in order to run the script /usr/run.pl on remote machines    xargs -P "$numprocs" -I '{}' -n  1 -- perl -e 'alarm shift; exec @ARGV' -- "$timeout" ssh -nxaq -o ConnectTimeout=5 -o StrictHostKeyChecking=no '{}' /usr/run.sh &lt; &lt;(echo -e "$node")    but I get on the console the following standard output   Connection to 143.6.22.4 closed by remote host.  xargs: perl: exited with status 255; aborting   where I need to put the 1>/dev/null in my syntax to avoid this message?
84722
I have this if in a bash script:  if [ $ACTION = deploy ]; then     ${JAVA_HOME}/bin/java ${JVM_ARGS} weblogic.WLST &lt;&lt; EOJ     connect('XXX','XXX','t3://XXX:8001')     jndi();     ls();     disconnect();     exit ();     EOJ else     echo "XXX" fi   I think the error is in the EOJ.
86678
I have a Param block in my script   Param (     [Parameter(Mandatory=$True)]     [string]$FileLocation,      [Parameter(Mandatory=$True)]     [string]$password = Read-Host "Type the password you would like to set all the users to" -assecurestring )   Can I use the Read-Host CmdLet in a required Parameter field? if not what can I do to make sure I take in the correct type of variable type so I can pass it to a user creation process?
110373
The script works fine if I run it with sh filename, but it ignores all the --exclude parameters if its run by cron:  #!/bin/sh TIMESTAMP=$(date +%u)  WEEK=`date +"%V"` if [ $(($WEEK%2)) -eq 0 ]; then     echo "even";     BACKUP_DIR="/mnt/backup/2_$TIMESTAMP"     mkdir -p "$BACKUP_DIR/www"  else     echo "odd";     BACKUP_DIR="/mnt/backup/1_$TIMESTAMP"     mkdir -p "$BACKUP_DIR/www"   fi  if [ $(date +%u) -gt 6 ]; then     zip -r -y $BACKUP_DIR/www/web.zip /var/www/ --exclude='var/www/\.opcache/*' --exclude='var/www/utils/phpThumb/cache/*' else     zip -r -y $BACKUP_DIR/www/web.zip /var/www/ --exclude='var/www/mycompany/files/*' --exclude='var/www/\.opcache/*' --exclude='var/www/mycompany/szamlazz/xml_szamlak/*' --exclude='var/www/mycompany/files_admin/szamlazz/*' --exclude='var/www/mycompany/files_admin/chatFiles/*' --exclude='var/www/mycompany/utils/phpThumb/cache/*' --exclude='*/backup-guard/*' --exclude='var/www/mycompany/mailer/*' --exclude='var/www/mycompany/attachments/*' fi  exit 0   The above script should create a larger backup on sunday, and a partial on weekdays, but it just zips everything.
105886
I'm trying to execute a string into my bash script. String contains variables (so I could substitute some CLI arguments depending on circumstances).  The problem is when I use variable containing --argument=value, everything breaks up, giving error:  Missing trailing-' in remote-shell command.   Example code:  #!/bin/bash  rsync_path="/usr/bin/rsync -azhrP" rsync_ssh_cmd="--rsh='ssh -o Compression=no'"  `$rsync_path /path/to/file $rsync_ssh_cmd username@localhost:/tmp`   If I just echo the last string from this code, it looks fine. But if i try to execute this string from script, it doesn't executes as expected.  I found a workaround - everything became OK if I try  eval "my-command-string"   instead of  `my-command-string`   or  (my-command-string)   Why does it so? How could I (should I really?) avoid to use eval?  I use bash 4.3.11(1)-release (x86_64-pc-linux-gnu) (Kubuntu 14.04.3).
89206
I am getting error:     The argument 2 of the "JSON_VALUE or JSON_QUERY" must be a string literal   ...while trying to pass variable as parameter to JSON_QUERY function. Please help me to resolve it.  DECLARE @cnt INT = 1; DECLARE @cnt_total INT = 1; DECLARE @json NVARCHAR(MAX); DECLARE @json1 NVARCHAR(MAX); declare @str  VARCHAR(200);  WHILE @cnt &lt;= 10 BEGIN     set @str = '$.Seasons[0].Products['+convert(varchar,@cnt)+'].ProductChannels';     set @str = char(39) +@str+ char(39);     PRINT @STR     select @json = json_query(jfile,@STR) from Import.tstjson; --MORE CODE         SET @cnt = @cnt + 1; END   Sample data:  {   "Seasons": [     {       "Season": "12321231",       "Products": [         {           "ProductId": "211",           "ProductChannels": [             {               "ChannelId": 1,               "WeekQuantities": []             }           ],           "ccc": 3,           "Tttt": 4         }       ]     }   ] }
74935
I have a JSON file members.json as below.  {    "took": 670,    "timed_out": false,    "_shards": {       "total": 8,       "successful": 8,       "failed": 0    },    "hits": {       "total": 74,       "max_score": 1,       "hits": [          {             "_index": "2000_270_0",             "_type": "Medical",             "_id": "02:17447847049147026174478:174159",             "_score": 1,             "_source": {                "memberId": "0x7b93910446f91928e23e1043dfdf5bcf",                "memberFirstName": "Uri",                "memberMiddleName": "Prayag",                "memberLastName": "Dubofsky"             }          },           {             "_index": "2000_270_0",             "_type": "Medical",             "_id": "02:17447847049147026174478:174159",             "_score": 1,             "_source": {                "memberId": "0x7b93910446f91928e23e1043dfdf5bcG",                "memberFirstName": "Uri",                "memberMiddleName": "Prayag",                "memberLastName": "Dubofsky"             }          }       ]    } }   I want to parse it using bash script get only the list of field memberId.   The expected output is:  memberIds -----------  0x7b93910446f91928e23e1043dfdf5bcf 0x7b93910446f91928e23e1043dfdf5bcG   I tried adding following bash+python code to .bashrc:  function getJsonVal() {    if [ \( $# -ne 1 \) -o \( -t 0 \) ]; then        echo "Usage: getJsonVal 'key' &lt; /tmp/file";        echo "   -- or -- ";        echo " cat /tmp/input | getJsonVal 'key'";        return;    fi;    cat | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["'$1'"]'; }   And then called:  $ cat members.json | getJsonVal "memberId"   But it throws:  Traceback (most recent call last):   File "&lt;string&gt;", line 1, in &lt;module&gt; KeyError: 'memberId'   Reference