single quote issue if i use function in bash [duplicate] - bash

This question already has answers here:
When to wrap quotes around a shell variable?
(5 answers)
Closed 11 months ago.
I have a script like below and I am running queries in mongodb. But when I call it as a function, it adds single quote and my query doesn't work. How can i solve this problem?
My Code:
mongo_func() {
mongo "$MONGO/$1" --quiet --eval $2 $3 $4
}
mongo_func "Users" 'db.ucol.updateMany({}, { $unset : {"name" : "", "Users": ""}});'
When I debug with bash -x, the output looks like below.
mongo 10.10.1.2/Users --quiet --eval 'db.ucol.updateMany({},' '{$unset:' '{"name"' : '"",' '"Users":' '""}});'
It s working as follows properly.
mongo 10.10.1.2/Users --quiet --eval 'db.ucol.updateMany({}, {$unset: {"name" : "", "Users": ""}});'

That's because you have failed to quote the function arguments.
Try this instead.
mongo_func() {
user=$1
shift
mongo "$MONGO/$user" --quiet --eval "$#"
}

Related

How to use sql query with Curl command

I have written a bash script using Curl command. I'm using an SQL query that gives a count of value 5. I want to assign that count value to T_4. Not sure how to do that in bash script using Curl command.
#!/bin/sh
result=$(
curl --netrc-file ~/.netrc -d '[
{
"T_1": "Test1",
"T_2": "Test2",
"T_3": "Test3",
"T_4": "1"
}
]' -X POST -H "Content-Type: application/json" https://www.testurl.com -d "SELECT count(5) FROM DUAL")
echo "Response from server"
echo $result
exit
Also, when I run the above script in putty, I'm getting an error that says -
"errorCode":"SIP-10322","errorMessage":"SIP-10322: rows updated is not 1:0"
Need your input on this.
The output of the SQL query which is a metric value, I have to use it in Rest call(Post API). Can anyone guide me on this?
Use command substitution to execute the query and assign the output to a shell variable. For instance, if the DB is MySQL, you would use:
t_4=$(mysql -e "SELECT 5 FROM DUAL")
Then use the variable inside the JSON parameter.
json='[
{
"T_1": "Test1",
"T_2": "Test2",
"T_3": "Test3",
"T_4": "'$t_4'"
}
]'
result=$(curl --netrc-file ~/.netrc -d "$json" -X POST -H "Content-Type: application/json" https://www.testurl.com)

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

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

How do I create a .bash_profile alias for a GroupMe bot's message command

I have a GroupMe bot that can send messages to the chat it is assigned to in this format:
curl -d '{"text" : "text", "bot_id" : "(REDACTED)"}' https://api.groupme.com/v3/bots/post
So, instead of typing up this monstrosity every time I wanted to send a message, I decided to create an alias for it.
Here is what I attempted to use in my .bash_profile for this:
alias groupmessage=groupmessagefunction
groupmessagefunction() { curl -d '{"text" : $1, "bot_id" : "(REDACTED)"}' https://api.groupme.com/v3/bots/post; }
Could anyone inform me what the correct formatting would be to get this to work? Thanks!
Update 1:
I now have my code as follows:
v="bot_id_string"
alias groupmessage=groupmessagefunction
groupmessagefunction() { curl -d '{"text" : '"$1"', "bot_id" : '"$v"'}' https://api.groupme.com/v3/bots/post; }
I would like to point out that what I am trying to accomplish is type in something like:
groupmessage "hello"
or
groupmessage hello
Then, it will send out the following command:
curl -d '{"text" : "hello", "bot_id" : "bot_id_string"}' https://api.groupme.com/v3/bots/post
I hope this helps clarify this question if any misunderstanding occurred.
Now, I hope this will be the solution for you:
v=bot_id
curl -d '{"text" : "Test", "'$v'" : "(REDACTED)"}' api.groupme.com/v3/bots/post
You have to use ' ' around $v --> '$v' because this will allow bash to evaluate $v inside curl -d ' ... ' .
Answer for your Update 1
As I see it would be the better way to use eval command:
v="bot_id_string"
alias groupmessage=groupmessagefunction
groupmessagefunction() {
a="curl -d '{\"text\" : \"$1\", \"bot_id\" : \"$v\"}' https://api.groupme.com/v3/bots/post"
echo "$a" # this echo just for checking
eval "$a"; }
groupmessage "Hello is it working now ?"

MongoDB - escaping quotes while inserting record

I have encountered a strange problem while I was trying to write a bash scritp to copy some data from one database to another.
To make things simple I will present the issue with the following example:
Let's say, we have a file in which are mongo insert commands that want to execute in mongo client. With Bash it will be:
cat file.json | mongo --verbose --host $HOST
This works fine until we use qoutes in records content.
For example:
use somedb;
db["collection"].insert({ "field": "test" })
#This of course works
db["collection"].insert({ "field": "test \" test" })
#But this doesn't
db["collection"].insert({ "field": "test \\" test" }) "#<-For syntax coloring
#I thounght maybe double quoting will help, but this also doesn't work
db["collection"].insert({ "field": "\"test\"" })
#This SUPRISINGLY works!!!
My question is, what is the propper way of escaping quotes for mongo client (I am using MongoDB shell verions: 2.2.4)?
Why when there is an even number of quotes in record, the script will succeed and with odd number will fail?
I will add that, there are no error messages. Mongo just fails silently(even with --verbose) and no new records appears in collection.
There's a JIRA ticket for this issue and it's fixed in 2.5.0.
For now, you can use the unicode point for double quote when inserting:
> db.foo.insert({ "field": "test \u0022 test" })
> db.foo.find()
{ "_id" : ObjectId("533455e563083f9b26efb5c2"), "field" : "test \" test" }

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