0

How to pass whole string also with quotation marks.

#!/bin/bash

my_name="My Value"

function abc(){
    a=$1
    echo $a
}

abc $my_name

This gives :

My

How to get the value as :

"My value"

also with quotation marks

Cyrus
  • 84,225
  • 14
  • 89
  • 153
supernatural
  • 1,107
  • 11
  • 34
  • 1
    The variable doesn't *have* quotation marks; the value of `my_name` is literally `My Value`; the quotes only exist to tell the shell that the space is part of the value, not separating the assignment `my_name=My` from the command `Value`. – chepner Jul 24 '20 at 16:03
  • Long discussion at [Security implications of forgetting to quote a variable in bash/POSIX shells](https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells) – glenn jackman Jul 24 '20 at 16:04

2 Answers2

1

Try enclosing in quotes instead of abc $my_name

abc "$my_name"

If you want quotes in your output too then try defining as:

my_name="\"My Value\""

and then type:

abc "$my_name"

Midha Tahir
  • 128
  • 2
  • 8
1

The easiest way to do this is to pass your argument within single quotes. This will consider your whole argument as a single string. Try this:

#!/bin/bash

my_name='"My Value"'

function abc(){
    a=$1
    echo "$a"
}

abc "$my_name"
chepner
  • 497,756
  • 71
  • 530
  • 681
Kebby
  • 314
  • 4
  • 10