Dataset Viewer
Auto-converted to Parquet Duplicate
QuestionId
stringlengths
3
8
QuestionTitle
stringlengths
15
149
QuestionScore
int64
1
27.2k
QuestionCreatedUtc
stringdate
2008-08-01 18:33:08
2025-06-16 04:59:48
QuestionBodyHtml
stringlengths
40
28.2k
QuestionViewCount
int64
78
16.5M
QuestionOwnerUserId
float64
4
25.2M
QuestionLastActivityUtc
stringdate
2008-09-08 19:26:01
2026-01-24 22:40:25
AcceptedAnswerId
int64
266
79.7M
AnswerScore
int64
2
30.1k
AnswerCreatedUtc
stringdate
2008-08-01 23:40:28
2025-06-16 05:23:39
AnswerOwnerUserId
float64
1
29.5M
AnswerLastActivityUtc
stringdate
2008-08-01 23:40:28
2026-01-23 17:46:09
QuestionLink
stringlengths
31
36
AnswerLink
stringlengths
31
36
AnswerBodyHtml
stringlengths
35
33k
AnswerBodyPreview
stringlengths
35
400
AllTagIdsCsv
stringlengths
2
37
AllTagNamesCsv
stringlengths
2
106
MergedQuestion
stringlengths
74
28.4k
quality_filter
stringclasses
10 values
unique_id
int64
0
29k
tag_major_lang
stringclasses
10 values
MergedQuestion_md
stringlengths
60
28.1k
AnswerBodyHtml_md
stringlengths
14
29.2k
59895
How do I get the directory where a Bash script is located from within the script itself?
6,405
2008-09-12 20:39:56
<p>How do I get the path of the directory in which a <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a> script is located, <em>inside</em> that script?</p> <p>I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:</p> <pre><code>$ ./application </code></pre>
2,834,402
2,908
2025-06-10 04:21:43
246,128
8,291
2008-10-29 08:36:45
7,412
2025-05-22 03:57:59
https://stackoverflow.com/q/59895
https://stackoverflow.com/a/246128
<pre><code>#!/usr/bin/env bash SCRIPT_DIR=$( cd -- &quot;$( dirname -- &quot;${BASH_SOURCE[0]}&quot; )&quot; &amp;&gt; /dev/null &amp;&amp; pwd ) </code></pre> <p>is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.</p> <p>It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:</p> <pre><code>#!/usr/bin/env bash get_script_dir() { local SOURCE_PATH=&quot;${BASH_SOURCE[0]}&quot; local SYMLINK_DIR local SCRIPT_DIR # Resolve symlinks recursively while [ -L &quot;$SOURCE_PATH&quot; ]; do # Get symlink directory SYMLINK_DIR=&quot;$( cd -P &quot;$( dirname &quot;$SOURCE_PATH&quot; )&quot; &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd )&quot; # Resolve symlink target (relative or absolute) SOURCE_PATH=&quot;$(readlink &quot;$SOURCE_PATH&quot;)&quot; # Check if candidate path is relative or absolute if [[ $SOURCE_PATH != /* ]]; then # Candidate path is relative, resolve to full path SOURCE_PATH=$SYMLINK_DIR/$SOURCE_PATH fi done # Get final script directory path from fully resolved source path SCRIPT_DIR=&quot;$(cd -P &quot;$( dirname &quot;$SOURCE_PATH&quot; )&quot; &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd)&quot; echo &quot;$SCRIPT_DIR&quot; } echo &quot;get_script_dir: $(get_script_dir)&quot; </code></pre> <p>This last one will work with any combination of aliases, <code>source</code>, <code>bash -c</code>, symlinks, etc.</p> <p><strong>Beware:</strong> if you <code>cd</code> to a different directory before running this snippet, the result may be incorrect!</p> <p>Also, watch out for <a href="http://bosker.wordpress.com/2012/02/12/bash-scripters-beware-of-the-cdpath/" rel="noreferrer"><code>$CDPATH</code> gotchas</a>, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling <code>update_terminal_cwd &gt;&amp;2</code> on Mac). Adding <code>&gt;/dev/null 2&gt;&amp;1</code> at the end of your <code>cd</code> command will take care of both possibilities.</p> <p>To understand how it works, try running this more verbose form:</p> <pre><code>#!/usr/bin/env bash SOURCE=${BASH_SOURCE[0]} while [ -L &quot;$SOURCE&quot; ]; do # resolve $SOURCE until the file is no longer a symlink TARGET=$(readlink &quot;$SOURCE&quot;) if [[ $TARGET == /* ]]; then echo &quot;SOURCE '$SOURCE' is an absolute symlink to '$TARGET'&quot; SOURCE=$TARGET else DIR=$( dirname &quot;$SOURCE&quot; ) echo &quot;SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')&quot; SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located fi done echo &quot;SOURCE is '$SOURCE'&quot; RDIR=$( dirname &quot;$SOURCE&quot; ) DIR=$( cd -P &quot;$( dirname &quot;$SOURCE&quot; )&quot; &gt;/dev/null 2&gt;&amp;1 &amp;&amp; pwd ) if [ &quot;$DIR&quot; != &quot;$RDIR&quot; ]; then echo &quot;DIR '$RDIR' resolves to '$DIR'&quot; fi echo &quot;DIR is '$DIR'&quot; </code></pre> <p>And it will print something like:</p> <pre class="lang-none prettyprint-override"><code>SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.') SOURCE is './sym2/scriptdir.sh' DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2' DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2' </code></pre>
<pre><code>#!/usr/bin/env bash SCRIPT_DIR=$( cd -- &quot;$( dirname -- &quot;${BASH_SOURCE[0]}&quot; )&quot; &amp;&gt; /dev/null &amp;&amp; pwd ) </code></pre> <p>is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.</p> <p>It will work as long as the last component of the path used to find the script is not a symlink (directory l
218, 387
bash, directory
<h1>How do I get the directory where a Bash script is located from within the script itself?</h1> <p>How do I get the path of the directory in which a <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a> script is located, <em>inside</em> that script?</p> <p>I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:</p> <pre><code>$ ./application </code></pre>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
16
bash
# How do I get the directory where a Bash script is located from within the script itself? How do I get the path of the directory in which a [Bash](http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29) script is located, *inside* that script? I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so: ``` $ ./application ```
``` #!/usr/bin/env bash SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) ``` is a useful one-liner which will give you the full directory name of the script no matter where it is being called from. It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution: ``` #!/usr/bin/env bash get_script_dir() { local SOURCE_PATH="${BASH_SOURCE[0]}" local SYMLINK_DIR local SCRIPT_DIR # Resolve symlinks recursively while [ -L "$SOURCE_PATH" ]; do # Get symlink directory SYMLINK_DIR="$( cd -P "$( dirname "$SOURCE_PATH" )" >/dev/null 2>&1 && pwd )" # Resolve symlink target (relative or absolute) SOURCE_PATH="$(readlink "$SOURCE_PATH")" # Check if candidate path is relative or absolute if [[ $SOURCE_PATH != /* ]]; then # Candidate path is relative, resolve to full path SOURCE_PATH=$SYMLINK_DIR/$SOURCE_PATH fi done # Get final script directory path from fully resolved source path SCRIPT_DIR="$(cd -P "$( dirname "$SOURCE_PATH" )" >/dev/null 2>&1 && pwd)" echo "$SCRIPT_DIR" } echo "get_script_dir: $(get_script_dir)" ``` This last one will work with any combination of aliases, `source`, `bash -c`, symlinks, etc. **Beware:** if you `cd` to a different directory before running this snippet, the result may be incorrect! Also, watch out for [`$CDPATH` gotchas](http://bosker.wordpress.com/2012/02/12/bash-scripters-beware-of-the-cdpath/), and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when calling `update_terminal_cwd >&2` on Mac). Adding `>/dev/null 2>&1` at the end of your `cd` command will take care of both possibilities. To understand how it works, try running this more verbose form: ``` #!/usr/bin/env bash SOURCE=${BASH_SOURCE[0]} while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink TARGET=$(readlink "$SOURCE") if [[ $TARGET == /* ]]; then echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'" SOURCE=$TARGET else DIR=$( dirname "$SOURCE" ) echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')" SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located fi done echo "SOURCE is '$SOURCE'" RDIR=$( dirname "$SOURCE" ) DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd ) if [ "$DIR" != "$RDIR" ]; then echo "DIR '$RDIR' resolves to '$DIR'" fi echo "DIR is '$DIR'" ``` And it will print something like: ``` SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.') SOURCE is './sym2/scriptdir.sh' DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2' DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2' ```
11304895
How do I copy a folder from remote to local using scp?
3,597
2012-07-03 05:17:58
<p>How do I copy a folder from remote to local host using <code>scp</code>?</p> <p>I use <code>ssh</code> to log in to my server.<br /> Then, I would like to copy the remote folder <code>foo</code> to local <code>/home/user/Desktop</code>.</p> <p>How do I achieve this?</p>
3,900,240
1,469,282
2024-09-17 16:05:15
11,304,926
6,406
2012-07-03 05:21:39
774,116
2020-10-15 01:21:14
https://stackoverflow.com/q/11304895
https://stackoverflow.com/a/11304926
<pre><code>scp -r user@your.server.example.com:/path/to/foo /home/user/Desktop/ </code></pre> <p>By not including the trailing '/' at the end of foo, you will copy the directory itself (including contents), rather than only the contents of the directory.</p> <p>From <code>man scp</code> (See <a href="http://man7.org/linux/man-pages/man1/scp.1.html" rel="noreferrer">online manual</a>)</p> <blockquote> <p>-r Recursively copy entire directories</p> </blockquote>
<pre><code>scp -r user@your.server.example.com:/path/to/foo /home/user/Desktop/ </code></pre> <p>By not including the trailing '/' at the end of foo, you will copy the directory itself (including contents), rather than only the contents of the directory.</p> <p>From <code>man scp</code> (See <a href="http://man7.org/linux/man-pages/man1/scp.1.html" rel="noreferrer">online manual</a>)</p> <blockquo
386, 390, 1231, 3149, 4330
command-line, copy, scp, shell, ssh
<h1>How do I copy a folder from remote to local using scp?</h1> <p>How do I copy a folder from remote to local host using <code>scp</code>?</p> <p>I use <code>ssh</code> to log in to my server.<br /> Then, I would like to copy the remote folder <code>foo</code> to local <code>/home/user/Desktop</code>.</p> <p>How do I achieve this?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
17
bash
# How do I copy a folder from remote to local using scp? How do I copy a folder from remote to local host using `scp`? I use `ssh` to log in to my server. Then, I would like to copy the remote folder `foo` to local `/home/user/Desktop`. How do I achieve this?
``` scp -r user@your.server.example.com:/path/to/foo /home/user/Desktop/ ``` By not including the trailing '/' at the end of foo, you will copy the directory itself (including contents), rather than only the contents of the directory. From `man scp` (See [online manual](http://man7.org/linux/man-pages/man1/scp.1.html)) > -r Recursively copy entire directories
59838
How do I check if a directory exists or not in a Bash shell script?
4,553
2008-09-12 20:06:25
<p>What command checks if a directory exists or not within a Bash shell script?</p>
3,495,129
4,120
2023-12-23 06:16:55
59,839
6,152
2008-09-12 20:07:06
4,120
2022-08-01 01:21:58
https://stackoverflow.com/q/59838
https://stackoverflow.com/a/59839
<p>To check if a directory exists:</p> <pre><code>if [ -d &quot;$DIRECTORY&quot; ]; then echo &quot;$DIRECTORY does exist.&quot; fi </code></pre> <p>To check if a directory does not exist:</p> <pre><code>if [ ! -d &quot;$DIRECTORY&quot; ]; then echo &quot;$DIRECTORY does not exist.&quot; fi </code></pre> <hr /> <p>However, as <a href="https://stackoverflow.com/users/1438/jon-ericson">Jon Ericson</a> points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check. E.g. running this:</p> <pre><code>ln -s &quot;$ACTUAL_DIR&quot; &quot;$SYMLINK&quot; if [ -d &quot;$SYMLINK&quot; ]; then rmdir &quot;$SYMLINK&quot; fi </code></pre> <p>Will produce the error message:</p> <pre class="lang-none prettyprint-override"><code>rmdir: failed to remove `symlink': Not a directory </code></pre> <p>So symbolic links may have to be treated differently, if subsequent commands expect directories:</p> <pre><code>if [ -d &quot;$LINK_OR_DIR&quot; ]; then if [ -L &quot;$LINK_OR_DIR&quot; ]; then # It is a symlink! # Symbolic link specific commands go here. rm &quot;$LINK_OR_DIR&quot; else # It's a directory! # Directory command goes here. rmdir &quot;$LINK_OR_DIR&quot; fi fi </code></pre> <hr /> <p>Take particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean <a href="https://stackoverflow.com/a/67458/102401">in another answer</a>.</p> <p>If the variables contain spaces or other unusual characters it will probably cause the script to fail.</p>
<p>To check if a directory exists:</p> <pre><code>if [ -d &quot;$DIRECTORY&quot; ]; then echo &quot;$DIRECTORY does exist.&quot; fi </code></pre> <p>To check if a directory does not exist:</p> <pre><code>if [ ! -d &quot;$DIRECTORY&quot; ]; then echo &quot;$DIRECTORY does not exist.&quot; fi </code></pre> <hr /> <p>However, as <a href="https://stackoverflow.com/users/1438/jon-ericson">Jon Erics
34, 387, 390, 1796, 1993
bash, command, posix, shell, unix
<h1>How do I check if a directory exists or not in a Bash shell script?</h1> <p>What command checks if a directory exists or not within a Bash shell script?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
18
bash
# How do I check if a directory exists or not in a Bash shell script? What command checks if a directory exists or not within a Bash shell script?
To check if a directory exists: ``` if [ -d "$DIRECTORY" ]; then echo "$DIRECTORY does exist." fi ``` To check if a directory does not exist: ``` if [ ! -d "$DIRECTORY" ]; then echo "$DIRECTORY does not exist." fi ``` --- However, as [Jon Ericson](https://stackoverflow.com/users/1438/jon-ericson) points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check. E.g. running this: ``` ln -s "$ACTUAL_DIR" "$SYMLINK" if [ -d "$SYMLINK" ]; then rmdir "$SYMLINK" fi ``` Will produce the error message: ``` rmdir: failed to remove `symlink': Not a directory ``` So symbolic links may have to be treated differently, if subsequent commands expect directories: ``` if [ -d "$LINK_OR_DIR" ]; then if [ -L "$LINK_OR_DIR" ]; then # It is a symlink! # Symbolic link specific commands go here. rm "$LINK_OR_DIR" else # It's a directory! # Directory command goes here. rmdir "$LINK_OR_DIR" fi fi ``` --- Take particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean [in another answer](https://stackoverflow.com/a/67458/102401). If the variables contain spaces or other unusual characters it will probably cause the script to fail.
89228
How do I execute a program or call a system command?
6,282
2008-09-18 01:35:30
<p>How do I call an external command within Python as if I had typed it in a shell or command prompt?</p>
5,200,895
17,085
2025-11-04 02:52:45
89,243
5,961
2008-09-18 01:39:35
11,465
2023-05-19 23:52:54
https://stackoverflow.com/q/89228
https://stackoverflow.com/a/89243
<p>Use <a href="https://docs.python.org/library/subprocess.html#subprocess.run" rel="noreferrer"><code>subprocess.run</code></a>:</p> <pre class="lang-py prettyprint-override"><code>import subprocess subprocess.run([&quot;ls&quot;, &quot;-l&quot;]) </code></pre> <p>Another common way is <a href="https://docs.python.org/library/os.html#os.system" rel="noreferrer"><code>os.system</code></a> but you shouldn't use it because it is unsafe if any parts of the command come from outside your program or can contain spaces or other special characters, also <code>subprocess.run</code> is generally more flexible (you can get the <a href="https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stdout" rel="noreferrer"><code>stdout</code></a>, <a href="https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stderr" rel="noreferrer"><code>stderr</code></a>, the <a href="https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.returncode" rel="noreferrer">&quot;real&quot; status code</a>, better <a href="https://docs.python.org/library/subprocess.html#subprocess.CalledProcessError" rel="noreferrer">error handling</a>, etc.). Even the <a href="https://docs.python.org/library/os.html#os.system" rel="noreferrer">documentation for <code>os.system</code></a> recommends using <code>subprocess</code> instead.</p> <p>On Python 3.4 and earlier, use <code>subprocess.call</code> instead of <code>.run</code>:</p> <pre class="lang-py prettyprint-override"><code>subprocess.call([&quot;ls&quot;, &quot;-l&quot;]) </code></pre>
<p>Use <a href="https://docs.python.org/library/subprocess.html#subprocess.run" rel="noreferrer"><code>subprocess.run</code></a>:</p> <pre class="lang-py prettyprint-override"><code>import subprocess subprocess.run([&quot;ls&quot;, &quot;-l&quot;]) </code></pre> <p>Another common way is <a href="https://docs.python.org/library/os.html#os.system" rel="noreferrer"><code>os.system</code></a> but yo
16, 390, 391, 1796, 2348
command, python, shell, subprocess, terminal
<h1>How do I execute a program or call a system command?</h1> <p>How do I call an external command within Python as if I had typed it in a shell or command prompt?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
19
bash
# How do I execute a program or call a system command? How do I call an external command within Python as if I had typed it in a shell or command prompt?
Use [`subprocess.run`](https://docs.python.org/library/subprocess.html#subprocess.run): ``` import subprocess subprocess.run(["ls", "-l"]) ``` Another common way is [`os.system`](https://docs.python.org/library/os.html#os.system) but you shouldn't use it because it is unsafe if any parts of the command come from outside your program or can contain spaces or other special characters, also `subprocess.run` is generally more flexible (you can get the [`stdout`](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stdout), [`stderr`](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stderr), the ["real" status code](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.returncode), better [error handling](https://docs.python.org/library/subprocess.html#subprocess.CalledProcessError), etc.). Even the [documentation for `os.system`](https://docs.python.org/library/os.html#os.system) recommends using `subprocess` instead. On Python 3.4 and earlier, use `subprocess.call` instead of `.run`: ``` subprocess.call(["ls", "-l"]) ```
638975
How do I tell if a file does not exist in Bash?
4,162
2009-03-12 14:48:43
<p>This checks if a file exists:</p> <pre><code>#!/bin/bash FILE=$1 if [ -f $FILE ]; then echo &quot;File $FILE exists.&quot; else echo &quot;File $FILE does not exist.&quot; fi </code></pre> <p>How do I only check if the file does <strong>not</strong> exist?</p>
3,439,075
1,288
2024-06-18 10:32:34
638,980
5,614
2009-03-12 14:50:01
75,170
2022-07-17 00:26:03
https://stackoverflow.com/q/638975
https://stackoverflow.com/a/638980
<p>The <a href="http://man7.org/linux/man-pages/man1/test.1.html" rel="noreferrer"><code>test</code></a> command (written as <code>[</code> here) has a &quot;not&quot; logical operator, <code>!</code> (exclamation mark):</p> <pre><code>if [ ! -f /tmp/foo.txt ]; then echo &quot;File not found!&quot; fi </code></pre>
<p>The <a href="http://man7.org/linux/man-pages/man1/test.1.html" rel="noreferrer"><code>test</code></a> command (written as <code>[</code> here) has a &quot;not&quot; logical operator, <code>!</code> (exclamation mark):</p> <pre><code>if [ ! -f /tmp/foo.txt ]; then echo &quot;File not found!&quot; fi </code></pre>
387, 531, 724
bash, file-io, scripting
<h1>How do I tell if a file does not exist in Bash?</h1> <p>This checks if a file exists:</p> <pre><code>#!/bin/bash FILE=$1 if [ -f $FILE ]; then echo &quot;File $FILE exists.&quot; else echo &quot;File $FILE does not exist.&quot; fi </code></pre> <p>How do I only check if the file does <strong>not</strong> exist?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
20
bash
# How do I tell if a file does not exist in Bash? This checks if a file exists: ``` #!/bin/bash FILE=$1 if [ -f $FILE ]; then echo "File $FILE exists." else echo "File $FILE does not exist." fi ``` How do I only check if the file does **not** exist?
The [`test`](http://man7.org/linux/man-pages/man1/test.1.html) command (written as `[` here) has a "not" logical operator, `!` (exclamation mark): ``` if [ ! -f /tmp/foo.txt ]; then echo "File not found!" fi ```
229551
How to check if a string contains a substring in Bash
3,658
2008-10-23 12:37:31
<p>I have a string in Bash:</p> <pre class="lang-sh prettyprint-override"><code>string=&quot;My string&quot; </code></pre> <p>How can I test if it contains another string?</p> <pre class="lang-sh prettyprint-override"><code>if [ $string ?? 'foo' ]; then echo &quot;It's there!&quot; fi </code></pre> <p>Where <code>??</code> is my unknown operator. Do I use <code>echo</code> and <code>grep</code>?</p> <pre class="lang-sh prettyprint-override"><code>if echo &quot;$string&quot; | grep 'foo'; then echo &quot;It's there!&quot; fi </code></pre> <p>That looks a bit clumsy.</p>
3,391,086
30,773
2026-01-08 11:58:40
229,606
5,028
2008-10-23 12:55:24
21,632
2020-04-17 01:20:42
https://stackoverflow.com/q/229551
https://stackoverflow.com/a/229606
<p>You can use <a href="https://stackoverflow.com/a/229585/3755692">Marcus's answer (* wildcards)</a> outside a case statement, too, if you use double brackets:</p> <pre><code>string='My long string' if [[ $string == *"My long"* ]]; then echo "It's there!" fi </code></pre> <p>Note that spaces in the needle string need to be placed between double quotes, and the <code>*</code> wildcards should be outside. Also note that a simple comparison operator is used (i.e. <code>==</code>), not the regex operator <code>=~</code>.</p>
<p>You can use <a href="https://stackoverflow.com/a/229585/3755692">Marcus's answer (* wildcards)</a> outside a case statement, too, if you use double brackets:</p> <pre><code>string='My long string' if [[ $string == *"My long"* ]]; then echo "It's there!" fi </code></pre> <p>Note that spaces in the needle string need to be placed between double quotes, and the <code>*</code> wildcards should
139, 387, 390, 4371, 10327
bash, sh, shell, string, substring
<h1>How to check if a string contains a substring in Bash</h1> <p>I have a string in Bash:</p> <pre class="lang-sh prettyprint-override"><code>string=&quot;My string&quot; </code></pre> <p>How can I test if it contains another string?</p> <pre class="lang-sh prettyprint-override"><code>if [ $string ?? 'foo' ]; then echo &quot;It's there!&quot; fi </code></pre> <p>Where <code>??</code> is my unknown operator. Do I use <code>echo</code> and <code>grep</code>?</p> <pre class="lang-sh prettyprint-override"><code>if echo &quot;$string&quot; | grep 'foo'; then echo &quot;It's there!&quot; fi </code></pre> <p>That looks a bit clumsy.</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
21
bash
# How to check if a string contains a substring in Bash I have a string in Bash: ``` string="My string" ``` How can I test if it contains another string? ``` if [ $string ?? 'foo' ]; then echo "It's there!" fi ``` Where `??` is my unknown operator. Do I use `echo` and `grep`? ``` if echo "$string" | grep 'foo'; then echo "It's there!" fi ``` That looks a bit clumsy.
You can use [Marcus's answer (* wildcards)](https://stackoverflow.com/a/229585/3755692) outside a case statement, too, if you use double brackets: ``` string='My long string' if [[ $string == *"My long"* ]]; then echo "It's there!" fi ``` Note that spaces in the needle string need to be placed between double quotes, and the `*` wildcards should be outside. Also note that a simple comparison operator is used (i.e. `==`), not the regex operator `=~`.
4181703
How to concatenate string variables in Bash
3,611
2010-11-15 05:38:35
<p>In PHP, strings are concatenated together as follows:</p> <pre><code>$foo = &quot;Hello&quot;; $foo .= &quot; World&quot;; </code></pre> <p>Here, <code>$foo</code> becomes <code>&quot;Hello World&quot;</code>.</p> <p>How is this accomplished in Bash?</p>
5,351,453
170,365
2025-10-16 09:01:13
4,181,721
4,890
2010-11-15 05:41:36
227,665
2019-09-01 12:51:28
https://stackoverflow.com/q/4181703
https://stackoverflow.com/a/4181721
<pre><code>foo="Hello" foo="${foo} World" echo "${foo}" &gt; Hello World </code></pre> <p>In general to concatenate two variables you can just write them one after another:</p> <pre><code>a='Hello' b='World' c="${a} ${b}" echo "${c}" &gt; Hello World </code></pre>
<pre><code>foo="Hello" foo="${foo} World" echo "${foo}" &gt; Hello World </code></pre> <p>In general to concatenate two variables you can just write them one after another:</p> <pre><code>a='Hello' b='World' c="${a} ${b}" echo "${c}" &gt; Hello World </code></pre>
367, 387, 390, 6050, 7792
bash, concatenation, shell, string-concatenation, syntax
<h1>How to concatenate string variables in Bash</h1> <p>In PHP, strings are concatenated together as follows:</p> <pre><code>$foo = &quot;Hello&quot;; $foo .= &quot; World&quot;; </code></pre> <p>Here, <code>$foo</code> becomes <code>&quot;Hello World&quot;</code>.</p> <p>How is this accomplished in Bash?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
22
bash
# How to concatenate string variables in Bash In PHP, strings are concatenated together as follows: ``` $foo = "Hello"; $foo .= " World"; ``` Here, `$foo` becomes `"Hello World"`. How is this accomplished in Bash?
``` foo="Hello" foo="${foo} World" echo "${foo}" > Hello World ``` In general to concatenate two variables you can just write them one after another: ``` a='Hello' b='World' c="${a} ${b}" echo "${c}" > Hello World ```
793858
How to mkdir only if a directory does not already exist?
2,998
2009-04-27 14:47:44
<p>I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the <code>mkdir</code> command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the "File exists" error that <code>mkdir</code> throws when it tries to create an existing directory. </p> <p>How can I best do this?</p>
2,292,191
73,371
2023-03-17 09:06:20
793,867
4,852
2009-04-27 14:49:46
69,755
2019-01-23 21:04:22
https://stackoverflow.com/q/793858
https://stackoverflow.com/a/793867
<p>Try <a href="http://pubs.opengroup.org/onlinepubs/009695399/utilities/mkdir.html" rel="noreferrer"><code>mkdir -p</code></a>:</p> <pre><code>mkdir -p foo </code></pre> <p>Note that this will also create any intermediate directories that don't exist; for instance,</p> <pre><code>mkdir -p foo/bar/baz </code></pre> <p>will create directories <code>foo</code>, <code>foo/bar</code>, and <code>foo/bar/baz</code> if they don't exist.</p> <p>Some implementation like GNU <code>mkdir</code> include <code>mkdir --parents</code> as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial Unixes, so it should be avoided.</p> <p>If you want an error when parent directories don't exist, and want to create the directory if it doesn't exist, then you can <a href="http://www.opengroup.org/onlinepubs/009695399/utilities/test.html" rel="noreferrer"><code>test</code></a> for the existence of the directory first:</p> <pre><code>[ -d foo ] || mkdir foo </code></pre>
<p>Try <a href="http://pubs.opengroup.org/onlinepubs/009695399/utilities/mkdir.html" rel="noreferrer"><code>mkdir -p</code></a>:</p> <pre><code>mkdir -p foo </code></pre> <p>Note that this will also create any intermediate directories that don't exist; for instance,</p> <pre><code>mkdir -p foo/bar/baz </code></pre> <p>will create directories <code>foo</code>, <code>foo/bar</code>, and <code>fo
390, 531, 989, 1964, 24423
aix, ksh, mkdir, scripting, shell
<h1>How to mkdir only if a directory does not already exist?</h1> <p>I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the <code>mkdir</code> command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the "File exists" error that <code>mkdir</code> throws when it tries to create an existing directory. </p> <p>How can I best do this?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
23
bash
# How to mkdir only if a directory does not already exist? I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the `mkdir` command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the "File exists" error that `mkdir` throws when it tries to create an existing directory. How can I best do this?
Try [`mkdir -p`](http://pubs.opengroup.org/onlinepubs/009695399/utilities/mkdir.html): ``` mkdir -p foo ``` Note that this will also create any intermediate directories that don't exist; for instance, ``` mkdir -p foo/bar/baz ``` will create directories `foo`, `foo/bar`, and `foo/bar/baz` if they don't exist. Some implementation like GNU `mkdir` include `mkdir --parents` as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial Unixes, so it should be avoided. If you want an error when parent directories don't exist, and want to create the directory if it doesn't exist, then you can [`test`](http://www.opengroup.org/onlinepubs/009695399/utilities/test.html) for the existence of the directory first: ``` [ -d foo ] || mkdir foo ```
592620
How can I check if a program exists from a Bash script?
3,215
2009-02-26 21:52:49
<p>How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script?</p> <p>It seems like it should be easy, but it's been stumping me.</p>
1,298,786
2,687
2025-06-01 11:10:42
677,212
4,596
2009-03-24 12:45:20
58,803
2025-06-01 11:10:42
https://stackoverflow.com/q/592620
https://stackoverflow.com/a/677212
<h2>Answer</h2> <p>POSIX compatible:</p> <pre><code>command -v &lt;the_command&gt; </code></pre> <p>Example use:</p> <pre><code>if ! command -v &lt;the_command&gt; &gt;/dev/null 2&gt;&amp;1 then echo &quot;&lt;the_command&gt; could not be found&quot; exit 1 fi </code></pre> <p>For Bash specific environments:</p> <pre><code>hash &lt;the_command&gt; # For regular commands. Or... type &lt;the_command&gt; # To check built-ins and keywords </code></pre> <h2>Explanation</h2> <p>Avoid <code>which</code>. Not only is it an external process you're launching for doing very little (meaning builtins like <code>hash</code>, <code>type</code> or <code>command</code> are way cheaper), you can also rely on the builtins to actually do what you want, while the effects of external commands can easily vary from system to system.</p> <p>Why care?</p> <ul> <li>Many operating systems have a <code>which</code> that <strong>doesn't even set an exit status</strong>, meaning the <code>if which foo</code> won't even work there and will <strong>always</strong> report that <code>foo</code> exists, even if it doesn't (note that some POSIX shells appear to do this for <code>hash</code> too).</li> <li>Many operating systems make <code>which</code> do custom and evil stuff like change the output or even hook into the package manager.</li> </ul> <p>So, don't use <code>which</code>. Instead use one of these:</p> <pre><code>command -v foo &gt;/dev/null 2&gt;&amp;1 || { echo &gt;&amp;2 &quot;I require foo but it's not installed. Aborting.&quot;; exit 1; } </code></pre> <pre><code>type foo &gt;/dev/null 2&gt;&amp;1 || { echo &gt;&amp;2 &quot;I require foo but it's not installed. Aborting.&quot;; exit 1; } </code></pre> <pre><code>hash foo 2&gt;/dev/null || { echo &gt;&amp;2 &quot;I require foo but it's not installed. Aborting.&quot;; exit 1; } </code></pre> <p>(Minor side-note: some will suggest <code>2&gt;&amp;-</code> is the same <code>2&gt;/dev/null</code> but shorter – <em>this is untrue</em>. <code>2&gt;&amp;-</code> closes FD 2 which causes an <strong>error</strong> in the program when it tries to write to stderr, which is very different from successfully writing to it and discarding the output (and dangerous!))<br /> (Additional minor side-note: some will suggest <code>&amp;&gt;/dev/null</code>, but this <a href="https://www.shellcheck.net/wiki/SC3020" rel="noreferrer">is not POSIX compliant</a>)</p> <p>If your hash bang is <code>/bin/sh</code> then you should care about what POSIX says. <code>type</code> and <code>hash</code>'s exit codes aren't terribly well defined by POSIX, and <code>hash</code> is seen to exit successfully when the command doesn't exist (haven't seen this with <code>type</code> yet). <code>command</code>'s exit status is well defined by POSIX, so that one is probably the safest to use.</p> <p>If your script uses <code>bash</code> though, POSIX rules don't really matter anymore and both <code>type</code> and <code>hash</code> become perfectly safe to use. <code>type</code> now has a <code>-P</code> to search just the <code>PATH</code> and <code>hash</code> has the side-effect that the command's location will be hashed (for faster lookup next time you use it), which is usually a good thing since you probably check for its existence in order to actually use it.</p> <p>As a simple example, here's a function that runs <code>gdate</code> if it exists, otherwise <code>date</code>:</p> <pre><code>gnudate() { if hash gdate 2&gt;/dev/null; then gdate &quot;$@&quot; else date &quot;$@&quot; fi } </code></pre>
<h2>Answer</h2> <p>POSIX compatible:</p> <pre><code>command -v &lt;the_command&gt; </code></pre> <p>Example use:</p> <pre><code>if ! command -v &lt;the_command&gt; &gt;/dev/null 2&gt;&amp;1 then echo &quot;&lt;the_command&gt; could not be found&quot; exit 1 fi </code></pre> <p>For Bash specific environments:</p> <pre><code>hash &lt;the_command&gt; # For regular commands. Or... type &lt;the
387
bash
<h1>How can I check if a program exists from a Bash script?</h1> <p>How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script?</p> <p>It seems like it should be easy, but it's been stumping me.</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
24
bash
# How can I check if a program exists from a Bash script? How would I validate that a program exists, in a way that will either return an error and exit, or continue with the script? It seems like it should be easy, but it's been stumping me.
## Answer POSIX compatible: ``` command -v <the_command> ``` Example use: ``` if ! command -v <the_command> >/dev/null 2>&1 then echo "<the_command> could not be found" exit 1 fi ``` For Bash specific environments: ``` hash <the_command> # For regular commands. Or... type <the_command> # To check built-ins and keywords ``` ## Explanation Avoid `which`. Not only is it an external process you're launching for doing very little (meaning builtins like `hash`, `type` or `command` are way cheaper), you can also rely on the builtins to actually do what you want, while the effects of external commands can easily vary from system to system. Why care? - Many operating systems have a `which` that **doesn't even set an exit status**, meaning the `if which foo` won't even work there and will **always** report that `foo` exists, even if it doesn't (note that some POSIX shells appear to do this for `hash` too). - Many operating systems make `which` do custom and evil stuff like change the output or even hook into the package manager. So, don't use `which`. Instead use one of these: ``` command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; } ``` ``` type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; } ``` ``` hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; } ``` (Minor side-note: some will suggest `2>&-` is the same `2>/dev/null` but shorter – *this is untrue*. `2>&-` closes FD 2 which causes an **error** in the program when it tries to write to stderr, which is very different from successfully writing to it and discarding the output (and dangerous!)) (Additional minor side-note: some will suggest `&>/dev/null`, but this [is not POSIX compliant](https://www.shellcheck.net/wiki/SC3020)) If your hash bang is `/bin/sh` then you should care about what POSIX says. `type` and `hash`'s exit codes aren't terribly well defined by POSIX, and `hash` is seen to exit successfully when the command doesn't exist (haven't seen this with `type` yet). `command`'s exit status is well defined by POSIX, so that one is probably the safest to use. If your script uses `bash` though, POSIX rules don't really matter anymore and both `type` and `hash` become perfectly safe to use. `type` now has a `-P` to search just the `PATH` and `hash` has the side-effect that the command's location will be hashed (for faster lookup next time you use it), which is usually a good thing since you probably check for its existence in order to actually use it. As a simple example, here's a function that runs `gdate` if it exists, otherwise `date`: ``` gnudate() { if hash gdate 2>/dev/null; then gdate "$@" else date "$@" fi } ```
965053
Extract filename and extension in Bash
2,918
2009-06-08 14:00:29
<p>I want to get the filename (without extension) and the extension separately.</p> <p>The best solution I found so far is:</p> <pre><code>NAME=`echo &quot;$FILE&quot; | cut -d'.' -f1` EXTENSION=`echo &quot;$FILE&quot; | cut -d'.' -f2` </code></pre> <p>This is wrong because it doesn't work if the file name contains multiple <code>.</code> characters. If, let's say, I have <code>a.b.js</code>, it will consider <code>a</code> and <code>b.js</code>, instead of <code>a.b</code> and <code>js</code>.</p> <p>It can be easily done in Python with</p> <pre class="lang-py prettyprint-override"><code>file, ext = os.path.splitext(path) </code></pre> <p>but I'd prefer not to fire up a Python interpreter just for this, if possible.</p> <p>Any better ideas?</p>
2,427,384
5,475
2025-08-17 16:24:24
965,072
4,538
2009-06-08 14:05:19
17,833
2025-03-21 07:22:40
https://stackoverflow.com/q/965053
https://stackoverflow.com/a/965072
<p>First, get file name without the path:</p> <pre class="lang-bash prettyprint-override"><code>filename=$(basename -- &quot;$fullfile&quot;) extension=&quot;${filename##*.}&quot; filename=&quot;${filename%.*}&quot; </code></pre> <p>Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions:</p> <pre class="lang-bash prettyprint-override"><code>filename=&quot;${fullfile##*/}&quot; </code></pre> <p>You may want to check the documentation :</p> <ul> <li>On the web at section &quot;<a href="http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">3.5.3 Shell Parameter Expansion</a>&quot;</li> <li>In the bash manpage at section called &quot;Parameter Expansion&quot;</li> </ul>
<p>First, get file name without the path:</p> <pre class="lang-bash prettyprint-override"><code>filename=$(basename -- &quot;$fullfile&quot;) extension=&quot;${filename##*.}&quot; filename=&quot;${filename%.*}&quot; </code></pre> <p>Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions:</p> <pre class="lang-bash
139, 387, 1062
bash, filenames, string
<h1>Extract filename and extension in Bash</h1> <p>I want to get the filename (without extension) and the extension separately.</p> <p>The best solution I found so far is:</p> <pre><code>NAME=`echo &quot;$FILE&quot; | cut -d'.' -f1` EXTENSION=`echo &quot;$FILE&quot; | cut -d'.' -f2` </code></pre> <p>This is wrong because it doesn't work if the file name contains multiple <code>.</code> characters. If, let's say, I have <code>a.b.js</code>, it will consider <code>a</code> and <code>b.js</code>, instead of <code>a.b</code> and <code>js</code>.</p> <p>It can be easily done in Python with</p> <pre class="lang-py prettyprint-override"><code>file, ext = os.path.splitext(path) </code></pre> <p>but I'd prefer not to fire up a Python interpreter just for this, if possible.</p> <p>Any better ideas?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
25
bash
# Extract filename and extension in Bash I want to get the filename (without extension) and the extension separately. The best solution I found so far is: ``` NAME=`echo "$FILE" | cut -d'.' -f1` EXTENSION=`echo "$FILE" | cut -d'.' -f2` ``` This is wrong because it doesn't work if the file name contains multiple `.` characters. If, let's say, I have `a.b.js`, it will consider `a` and `b.js`, instead of `a.b` and `js`. It can be easily done in Python with ``` file, ext = os.path.splitext(path) ``` but I'd prefer not to fire up a Python interpreter just for this, if possible. Any better ideas?
First, get file name without the path: ``` filename=$(basename -- "$fullfile") extension="${filename##*.}" filename="${filename%.*}" ``` Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions: ``` filename="${fullfile##*/}" ``` You may want to check the documentation : - On the web at section "[3.5.3 Shell Parameter Expansion](http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html)" - In the bash manpage at section called "Parameter Expansion"
5905054
How can I recursively find all files in current and subfolders based on wildcard matching?
3,144
2011-05-05 23:01:34
<p>How can I recursively find all files in current and subfolders based on wildcard matching?</p>
5,129,961
302,064
2023-12-29 09:16:26
5,905,066
4,478
2011-05-05 23:03:37
82,219
2023-12-29 09:16:26
https://stackoverflow.com/q/5905054
https://stackoverflow.com/a/5905066
<p>Use <a href="http://linux.die.net/man/1/find" rel="noreferrer"><code>find</code></a>:</p> <pre><code>find . -name &quot;foo*&quot; </code></pre> <p><code>find</code> needs a starting point, so the <code>.</code> (dot) points to the current directory.</p> <p>If you need <strong>case insensitive</strong> search use :</p> <pre><code>find . -iname &quot;foo*&quot; </code></pre>
<p>Use <a href="http://linux.die.net/man/1/find" rel="noreferrer"><code>find</code></a>:</p> <pre><code>find . -name &quot;foo*&quot; </code></pre> <p><code>find</code> needs a starting point, so the <code>.</code> (dot) points to the current directory.</p> <p>If you need <strong>case insensitive</strong> search use :</p> <pre><code>find . -iname &quot;foo*&quot; </code></pre>
58, 390
linux, shell
<h1>How can I recursively find all files in current and subfolders based on wildcard matching?</h1> <p>How can I recursively find all files in current and subfolders based on wildcard matching?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
26
bash
# How can I recursively find all files in current and subfolders based on wildcard matching? How can I recursively find all files in current and subfolders based on wildcard matching?
Use [`find`](http://linux.die.net/man/1/find): ``` find . -name "foo*" ``` `find` needs a starting point, so the `.` (dot) points to the current directory. If you need **case insensitive** search use : ``` find . -iname "foo*" ```
8467424
Echo newline in Bash prints literal \n
3,667
2011-12-11 21:01:54
<p>How do I print a newline? This merely prints <code>\n</code>:</p> <pre><code>echo -e &quot;Hello,\nWorld!&quot; </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>Hello,\nWorld! </code></pre>
3,688,424
187,644
2025-12-09 22:55:19
8,467,449
4,311
2011-12-11 21:04:56
56,338
2025-07-16 17:42:38
https://stackoverflow.com/q/8467424
https://stackoverflow.com/a/8467449
<p>Use <code>printf</code> instead:</p> <pre><code>printf 'Hello, \nWorld!\n' </code></pre> <p><code>printf</code> behaves more consistently across different environments than <code>echo</code>.</p>
<p>Use <code>printf</code> instead:</p> <pre><code>printf 'Hello, \nWorld!\n' </code></pre> <p><code>printf</code> behaves more consistently across different environments than <code>echo</code>.</p>
387, 3705, 13824
bash, echo, newline
<h1>Echo newline in Bash prints literal \n</h1> <p>How do I print a newline? This merely prints <code>\n</code>:</p> <pre><code>echo -e &quot;Hello,\nWorld!&quot; </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>Hello,\nWorld! </code></pre>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
27
bash
# Echo newline in Bash prints literal \n How do I print a newline? This merely prints `\n`: ``` echo -e "Hello,\nWorld!" ``` Output: ``` Hello,\nWorld! ```
Use `printf` instead: ``` printf 'Hello, \nWorld!\n' ``` `printf` behaves more consistently across different environments than `echo`.
1825585
Determine installed PowerShell version
2,915
2009-12-01 11:30:03
<p>How can I determine what version of PowerShell is installed on a computer, and indeed if it is installed at all?</p>
3,250,810
35,483
2025-11-15 13:22:28
1,825,807
3,878
2009-12-01 12:12:38
null
2020-01-02 07:33:10
https://stackoverflow.com/q/1825585
https://stackoverflow.com/a/1825807
<p>Use <code>$PSVersionTable.PSVersion</code> to determine the engine version. If the variable does not exist, it is safe to assume the engine is version <code>1.0</code>.</p> <p>Note that <code>$Host.Version</code> and <code>(Get-Host).Version</code> are not reliable - they reflect the version of the host only, not the engine. PowerGUI, PowerShellPLUS, etc. are all hosting applications, and they will set the host's version to reflect their product version&nbsp;&mdash; which is entirely correct, but not what you're looking for.</p> <pre><code>PS C:\&gt; $PSVersionTable.PSVersion Major Minor Build Revision ----- ----- ----- -------- 4 0 -1 -1 </code></pre>
<p>Use <code>$PSVersionTable.PSVersion</code> to determine the engine version. If the variable does not exist, it is safe to assume the engine is version <code>1.0</code>.</p> <p>Note that <code>$Host.Version</code> and <code>(Get-Host).Version</code> are not reliable - they reflect the version of the host only, not the engine. PowerGUI, PowerShellPLUS, etc. are all hosting applications, and they
526, 5792
powershell, version
<h1>Determine installed PowerShell version</h1> <p>How can I determine what version of PowerShell is installed on a computer, and indeed if it is installed at all?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
28
bash
# Determine installed PowerShell version How can I determine what version of PowerShell is installed on a computer, and indeed if it is installed at all?
Use `$PSVersionTable.PSVersion` to determine the engine version. If the variable does not exist, it is safe to assume the engine is version `1.0`. Note that `$Host.Version` and `(Get-Host).Version` are not reliable - they reflect the version of the host only, not the engine. PowerGUI, PowerShellPLUS, etc. are all hosting applications, and they will set the host's version to reflect their product version — which is entirely correct, but not what you're looking for. ``` PS C:\> $PSVersionTable.PSVersion Major Minor Build Revision ----- ----- ----- -------- 4 0 -1 -1 ```
192249
How do I parse command line arguments in Bash?
2,627
2008-10-10 16:57:19
<p>Say, I have a script that gets called with this line:</p> <pre><code>./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile </code></pre> <p>or this one:</p> <pre><code>./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile </code></pre> <p>What's the accepted way of parsing this such that in each case (or some combination of the two) <code>$v</code>, <code>$f</code>, and <code>$d</code> will all be set to <code>true</code> and <code>$outFile</code> will be equal to <code>/fizz/someOtherFile</code>?</p>
2,195,200
1,512
2025-05-30 12:27:53
14,203,146
3,687
2013-01-07 20:01:05
117,471
2024-03-18 06:12:10
https://stackoverflow.com/q/192249
https://stackoverflow.com/a/14203146
<h4>Bash Space-Separated (e.g., <code>--option argument</code>)</h4> <pre class="lang-bash prettyprint-override"><code>cat &gt;/tmp/demo-space-separated.sh &lt;&lt;'EOF' #!/bin/bash POSITIONAL_ARGS=() while [[ $# -gt 0 ]]; do case $1 in -e|--extension) EXTENSION=&quot;$2&quot; shift # past argument shift # past value ;; -s|--searchpath) SEARCHPATH=&quot;$2&quot; shift # past argument shift # past value ;; --default) DEFAULT=YES shift # past argument ;; -*|--*) echo &quot;Unknown option $1&quot; exit 1 ;; *) POSITIONAL_ARGS+=(&quot;$1&quot;) # save positional arg shift # past argument ;; esac done set -- &quot;${POSITIONAL_ARGS[@]}&quot; # restore positional parameters echo &quot;FILE EXTENSION = ${EXTENSION}&quot; echo &quot;SEARCH PATH = ${SEARCHPATH}&quot; echo &quot;DEFAULT = ${DEFAULT}&quot; echo &quot;Number files in SEARCH PATH with EXTENSION:&quot; $(ls -1 &quot;${SEARCHPATH}&quot;/*.&quot;${EXTENSION}&quot; | wc -l) if [[ -n $1 ]]; then echo &quot;Last line of file specified as non-opt/last argument:&quot; tail -1 &quot;$1&quot; fi EOF chmod +x /tmp/demo-space-separated.sh /tmp/demo-space-separated.sh -e conf -s /etc /etc/hosts </code></pre> <h5>Output from copy-pasting the block above</h5> <pre class="lang-bash prettyprint-override"><code>FILE EXTENSION = conf SEARCH PATH = /etc DEFAULT = Number files in SEARCH PATH with EXTENSION: 14 Last line of file specified as non-opt/last argument: #93.184.216.34 example.com </code></pre> <h5>Usage</h5> <pre class="lang-bash prettyprint-override"><code>demo-space-separated.sh -e conf -s /etc /etc/hosts </code></pre> <hr /> <h4>Bash Equals-Separated (e.g., <code>--option=argument</code>)</h4> <pre class="lang-bash prettyprint-override"><code>cat &gt;/tmp/demo-equals-separated.sh &lt;&lt;'EOF' #!/bin/bash for i in &quot;$@&quot;; do case $i in -e=*|--extension=*) EXTENSION=&quot;${i#*=}&quot; shift # past argument=value ;; -s=*|--searchpath=*) SEARCHPATH=&quot;${i#*=}&quot; shift # past argument=value ;; --default) DEFAULT=YES shift # past argument with no value ;; -*|--*) echo &quot;Unknown option $i&quot; exit 1 ;; *) ;; esac done echo &quot;FILE EXTENSION = ${EXTENSION}&quot; echo &quot;SEARCH PATH = ${SEARCHPATH}&quot; echo &quot;DEFAULT = ${DEFAULT}&quot; echo &quot;Number files in SEARCH PATH with EXTENSION:&quot; $(ls -1 &quot;${SEARCHPATH}&quot;/*.&quot;${EXTENSION}&quot; | wc -l) if [[ -n $1 ]]; then echo &quot;Last line of file specified as non-opt/last argument:&quot; tail -1 $1 fi EOF chmod +x /tmp/demo-equals-separated.sh /tmp/demo-equals-separated.sh -e=conf -s=/etc /etc/hosts </code></pre> <h5>Output from copy-pasting the block above</h5> <pre class="lang-bash prettyprint-override"><code>FILE EXTENSION = conf SEARCH PATH = /etc DEFAULT = Number files in SEARCH PATH with EXTENSION: 14 Last line of file specified as non-opt/last argument: #93.184.216.34 example.com </code></pre> <h5>Usage</h5> <pre class="lang-bash prettyprint-override"><code>demo-equals-separated.sh -e=conf -s=/etc /etc/hosts </code></pre> <hr /> <p>To better understand <code>${i#*=}</code> search for &quot;Substring Removal&quot; in <a href="http://tldp.org/LDP/abs/html/string-manipulation.html" rel="noreferrer">this guide</a>. It is functionally equivalent to <code>`sed 's/[^=]*=//' &lt;&lt;&lt; &quot;$i&quot;`</code> which calls a needless subprocess or <code>`echo &quot;$i&quot; | sed 's/[^=]*=//'`</code> which calls <em>two</em> needless subprocesses.</p> <hr /> <h4>Using bash with getopt[s]</h4> <p>getopt(1) limitations (older, relatively-recent <code>getopt</code> versions):</p> <ul> <li>can't handle arguments that are empty strings</li> <li>can't handle arguments with embedded whitespace</li> </ul> <p>More recent <code>getopt</code> versions don't have these limitations. For more information, see these <a href="https://mywiki.wooledge.org/BashFAQ/035#getopts" rel="noreferrer">docs</a>.</p> <hr /> <h4>POSIX getopts</h4> <p>Additionally, the POSIX shell and others offer <code>getopts</code> which doen't have these limitations. I've included a simplistic <code>getopts</code> example.</p> <pre class="lang-bash prettyprint-override"><code>cat &gt;/tmp/demo-getopts.sh &lt;&lt;'EOF' #!/bin/sh # A POSIX variable OPTIND=1 # Reset in case getopts has been used previously in the shell. # Initialize our own variables: output_file=&quot;&quot; verbose=0 while getopts &quot;h?vf:&quot; opt; do case &quot;$opt&quot; in h|\?) show_help exit 0 ;; v) verbose=1 ;; f) output_file=$OPTARG ;; esac done shift $((OPTIND-1)) [ &quot;${1:-}&quot; = &quot;--&quot; ] &amp;&amp; shift echo &quot;verbose=$verbose, output_file='$output_file', Leftovers: $@&quot; EOF chmod +x /tmp/demo-getopts.sh /tmp/demo-getopts.sh -vf /etc/hosts foo bar </code></pre> <h5>Output from copy-pasting the block above</h5> <pre class="lang-bash prettyprint-override"><code>verbose=1, output_file='/etc/hosts', Leftovers: foo bar </code></pre> <h5>Usage</h5> <pre class="lang-bash prettyprint-override"><code>demo-getopts.sh -vf /etc/hosts foo bar </code></pre> <p>The advantages of <code>getopts</code> are:</p> <ol> <li>It's more portable, and will work in other shells like <code>dash</code>.</li> <li>It can handle multiple single options like <code>-vf filename</code> in the typical Unix way, automatically.</li> </ol> <p>The disadvantage of <code>getopts</code> is that it can only handle short options (<code>-h</code>, not <code>--help</code>) without additional code.</p> <p>There is a <a href="https://flokoe.github.io/bash-hackers-wiki/howto/getopts_tutorial" rel="noreferrer">getopts tutorial</a> which explains what all of the syntax and variables mean. In bash, there is also <code>help getopts</code>, which might be informative.</p>
<h4>Bash Space-Separated (e.g., <code>--option argument</code>)</h4> <pre class="lang-bash prettyprint-override"><code>cat &gt;/tmp/demo-space-separated.sh &lt;&lt;'EOF' #!/bin/bash POSITIONAL_ARGS=() while [[ $# -gt 0 ]]; do case $1 in -e|--extension) EXTENSION=&quot;$2&quot; shift # past argument shift # past value ;; -s|--searchpath) SEARCHPATH=&quot;$
387, 531, 1231, 2313, 19020
arguments, bash, command-line, getopts, scripting
<h1>How do I parse command line arguments in Bash?</h1> <p>Say, I have a script that gets called with this line:</p> <pre><code>./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile </code></pre> <p>or this one:</p> <pre><code>./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile </code></pre> <p>What's the accepted way of parsing this such that in each case (or some combination of the two) <code>$v</code>, <code>$f</code>, and <code>$d</code> will all be set to <code>true</code> and <code>$outFile</code> will be equal to <code>/fizz/someOtherFile</code>?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
29
bash
# How do I parse command line arguments in Bash? Say, I have a script that gets called with this line: ``` ./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile ``` or this one: ``` ./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile ``` What's the accepted way of parsing this such that in each case (or some combination of the two) `$v`, `$f`, and `$d` will all be set to `true` and `$outFile` will be equal to `/fizz/someOtherFile`?
#### Bash Space-Separated (e.g., `--option argument`) ``` cat >/tmp/demo-space-separated.sh <<'EOF' #!/bin/bash POSITIONAL_ARGS=() while [[ $# -gt 0 ]]; do case $1 in -e|--extension) EXTENSION="$2" shift # past argument shift # past value ;; -s|--searchpath) SEARCHPATH="$2" shift # past argument shift # past value ;; --default) DEFAULT=YES shift # past argument ;; -*|--*) echo "Unknown option $1" exit 1 ;; *) POSITIONAL_ARGS+=("$1") # save positional arg shift # past argument ;; esac done set -- "${POSITIONAL_ARGS[@]}" # restore positional parameters echo "FILE EXTENSION = ${EXTENSION}" echo "SEARCH PATH = ${SEARCHPATH}" echo "DEFAULT = ${DEFAULT}" echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l) if [[ -n $1 ]]; then echo "Last line of file specified as non-opt/last argument:" tail -1 "$1" fi EOF chmod +x /tmp/demo-space-separated.sh /tmp/demo-space-separated.sh -e conf -s /etc /etc/hosts ``` ##### Output from copy-pasting the block above ``` FILE EXTENSION = conf SEARCH PATH = /etc DEFAULT = Number files in SEARCH PATH with EXTENSION: 14 Last line of file specified as non-opt/last argument: #93.184.216.34 example.com ``` ##### Usage ``` demo-space-separated.sh -e conf -s /etc /etc/hosts ``` --- #### Bash Equals-Separated (e.g., `--option=argument`) ``` cat >/tmp/demo-equals-separated.sh <<'EOF' #!/bin/bash for i in "$@"; do case $i in -e=*|--extension=*) EXTENSION="${i#*=}" shift # past argument=value ;; -s=*|--searchpath=*) SEARCHPATH="${i#*=}" shift # past argument=value ;; --default) DEFAULT=YES shift # past argument with no value ;; -*|--*) echo "Unknown option $i" exit 1 ;; *) ;; esac done echo "FILE EXTENSION = ${EXTENSION}" echo "SEARCH PATH = ${SEARCHPATH}" echo "DEFAULT = ${DEFAULT}" echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l) if [[ -n $1 ]]; then echo "Last line of file specified as non-opt/last argument:" tail -1 $1 fi EOF chmod +x /tmp/demo-equals-separated.sh /tmp/demo-equals-separated.sh -e=conf -s=/etc /etc/hosts ``` ##### Output from copy-pasting the block above ``` FILE EXTENSION = conf SEARCH PATH = /etc DEFAULT = Number files in SEARCH PATH with EXTENSION: 14 Last line of file specified as non-opt/last argument: #93.184.216.34 example.com ``` ##### Usage ``` demo-equals-separated.sh -e=conf -s=/etc /etc/hosts ``` --- To better understand `${i#*=}` search for "Substring Removal" in [this guide](http://tldp.org/LDP/abs/html/string-manipulation.html). It is functionally equivalent to `` `sed 's/[^=]*=//' <<< "$i"` `` which calls a needless subprocess or `` `echo "$i" | sed 's/[^=]*=//'` `` which calls *two* needless subprocesses. --- #### Using bash with getopt[s] getopt(1) limitations (older, relatively-recent `getopt` versions): - can't handle arguments that are empty strings - can't handle arguments with embedded whitespace More recent `getopt` versions don't have these limitations. For more information, see these [docs](https://mywiki.wooledge.org/BashFAQ/035#getopts). --- #### POSIX getopts Additionally, the POSIX shell and others offer `getopts` which doen't have these limitations. I've included a simplistic `getopts` example. ``` cat >/tmp/demo-getopts.sh <<'EOF' #!/bin/sh # A POSIX variable OPTIND=1 # Reset in case getopts has been used previously in the shell. # Initialize our own variables: output_file="" verbose=0 while getopts "h?vf:" opt; do case "$opt" in h|\?) show_help exit 0 ;; v) verbose=1 ;; f) output_file=$OPTARG ;; esac done shift $((OPTIND-1)) [ "${1:-}" = "--" ] && shift echo "verbose=$verbose, output_file='$output_file', Leftovers: $@" EOF chmod +x /tmp/demo-getopts.sh /tmp/demo-getopts.sh -vf /etc/hosts foo bar ``` ##### Output from copy-pasting the block above ``` verbose=1, output_file='/etc/hosts', Leftovers: foo bar ``` ##### Usage ``` demo-getopts.sh -vf /etc/hosts foo bar ``` The advantages of `getopts` are: 1. It's more portable, and will work in other shells like `dash`. 2. It can handle multiple single options like `-vf filename` in the typical Unix way, automatically. The disadvantage of `getopts` is that it can only handle short options (`-h`, not `--help`) without additional code. There is a [getopts tutorial](https://flokoe.github.io/bash-hackers-wiki/howto/getopts_tutorial) which explains what all of the syntax and variables mean. In bash, there is also `help getopts`, which might be informative.
818255
What does " 2>&1 " mean?
3,260
2009-05-03 22:57:00
<p>To combine <code>stderr</code> and <code>stdout</code> into the <code>stdout</code> stream, we append this to a command:</p> <pre><code>2&gt;&amp;1 </code></pre> <p>For example, the following command shows the first few errors from compiling <code>main.cpp</code>:</p> <pre><code>g++ main.cpp 2&gt;&amp;1 | head </code></pre> <p>But what does <code>2&gt;&amp;1</code> mean?</p>
1,963,820
30,529
2024-11-07 14:50:17
818,284
3,676
2009-05-03 23:04:53
40,005
2022-07-17 06:18:24
https://stackoverflow.com/q/818255
https://stackoverflow.com/a/818284
<p>File descriptor 1 is the standard output (<code>stdout</code>).<br> File descriptor 2 is the standard error (<code>stderr</code>).</p> <p>At first, <code>2&gt;1</code> may look like a good way to redirect <code>stderr</code> to <code>stdout</code>. However, it will actually be interpreted as &quot;redirect <code>stderr</code> to a file named <code>1</code>&quot;.</p> <p><code>&amp;</code> indicates that what follows and precedes is a <em>file descriptor</em>, and not a filename. Thus, we use <code>2&gt;&amp;1</code>. Consider <code>&gt;&amp;</code> to be a redirect merger operator.</p>
<p>File descriptor 1 is the standard output (<code>stdout</code>).<br> File descriptor 2 is the standard error (<code>stderr</code>).</p> <p>At first, <code>2&gt;1</code> may look like a good way to redirect <code>stderr</code> to <code>stdout</code>. However, it will actually be interpreted as &quot;redirect <code>stderr</code> to a file named <code>1</code>&quot;.</p> <p><code>&amp;</code> indic
34, 387, 390
bash, shell, unix
<h1>What does " 2>&1 " mean?</h1> <p>To combine <code>stderr</code> and <code>stdout</code> into the <code>stdout</code> stream, we append this to a command:</p> <pre><code>2&gt;&amp;1 </code></pre> <p>For example, the following command shows the first few errors from compiling <code>main.cpp</code>:</p> <pre><code>g++ main.cpp 2&gt;&amp;1 | head </code></pre> <p>But what does <code>2&gt;&amp;1</code> mean?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
30
bash
# What does " 2>&1 " mean? To combine `stderr` and `stdout` into the `stdout` stream, we append this to a command: ``` 2>&1 ``` For example, the following command shows the first few errors from compiling `main.cpp`: ``` g++ main.cpp 2>&1 | head ``` But what does `2>&1` mean?
File descriptor 1 is the standard output (`stdout`). File descriptor 2 is the standard error (`stderr`). At first, `2>1` may look like a good way to redirect `stderr` to `stdout`. However, it will actually be interpreted as "redirect `stderr` to a file named `1`". `&` indicates that what follows and precedes is a *file descriptor*, and not a filename. Thus, we use `2>&1`. Consider `>&` to be a redirect merger operator.
4037939
PowerShell says "execution of scripts is disabled on this system."
3,013
2010-10-27 21:39:29
<p>I am trying to run a <code>cmd</code> file that calls a PowerShell script from <code>cmd.exe</code>, but I am getting this error:</p> <blockquote> <p><code>Management_Install.ps1</code> cannot be loaded because the execution of scripts is disabled on this system.</p> </blockquote> <p>I ran this command:</p> <pre class="lang-none prettyprint-override"><code>Set-ExecutionPolicy -ExecutionPolicy Unrestricted </code></pre> <p>When I run <code>Get-ExecutionPolicy</code> from PowerShell, it returns <code>Unrestricted</code>.</p> <pre class="lang-none prettyprint-override"><code>Get-ExecutionPolicy </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>Unrestricted </code></pre> <hr /> <blockquote> <p>cd &quot;C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts&quot; powershell .\Management_Install.ps1 1</p> <p>WARNING: Running x86 PowerShell...</p> <p>File <code>C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts\Management_Install.ps1</code> cannot be loaded because the execution of scripts is disabled on this system. Please see &quot;<code>get-help about_signing</code>&quot; for more details.</p> <p>At line:1 char:25</p> <ul> <li><p><code>.\Management_Install.ps1</code> &lt;&lt;&lt;&lt; 1</p> <ul> <li><p>CategoryInfo : NotSpecified: (:) [], PSSecurityException</p> </li> <li><p>FullyQualifiedErrorId : RuntimeException</p> </li> </ul> </li> </ul> <p>C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts&gt; PAUSE</p> <p>Press any key to continue . . .</p> </blockquote> <hr /> <p>The system is <a href="https://en.wikipedia.org/wiki/Windows_Server_2008" rel="noreferrer">Windows Server 2008</a> R2.</p> <p>What am I doing wrong?</p>
5,280,444
489,400
2025-08-24 19:14:52
4,038,991
3,670
2010-10-28 01:16:25
135,965
2022-02-24 18:26:00
https://stackoverflow.com/q/4037939
https://stackoverflow.com/a/4038991
<p>If you're using <a href="https://en.wikipedia.org/wiki/Windows_Server_2008" rel="noreferrer">Windows Server 2008</a> R2 then there is an <em>x64</em> and <em>x86</em> version of PowerShell both of which have to have their execution policies set. Did you set the execution policy on both hosts?</p> <p>As an <em>Administrator</em>, you can set the execution policy by typing this into your PowerShell window:</p> <pre class="lang-None prettyprint-override"><code>Set-ExecutionPolicy RemoteSigned </code></pre> <p>For more information, see <em><a href="https://learn.microsoft.com/powershell/module/microsoft.powershell.security/set-executionpolicy" rel="noreferrer">Using the Set-ExecutionPolicy Cmdlet</a></em>.</p> <p>When you are done, you can set the policy back to its default value with:</p> <pre class="lang-None prettyprint-override"><code>Set-ExecutionPolicy Restricted </code></pre> <p>You may see an error:</p> <pre class="lang-None prettyprint-override"><code>Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. To change the execution policy for the default (LocalMachine) scope, start Windows PowerShell with the &quot;Run as administrator&quot; option. To change the execution policy for the current user, run &quot;Set-ExecutionPolicy -Scope CurrentUser&quot;. </code></pre> <p>So you may need to run the command like this (as seen in comments):</p> <pre class="lang-None prettyprint-override"><code>Set-ExecutionPolicy RemoteSigned -Scope CurrentUser </code></pre>
<p>If you're using <a href="https://en.wikipedia.org/wiki/Windows_Server_2008" rel="noreferrer">Windows Server 2008</a> R2 then there is an <em>x64</em> and <em>x86</em> version of PowerShell both of which have to have their execution policies set. Did you set the execution policy on both hosts?</p> <p>As an <em>Administrator</em>, you can set the execution policy by typing this into your PowerShe
526, 36466
powershell, windows-server-2008-r2
<h1>PowerShell says "execution of scripts is disabled on this system."</h1> <p>I am trying to run a <code>cmd</code> file that calls a PowerShell script from <code>cmd.exe</code>, but I am getting this error:</p> <blockquote> <p><code>Management_Install.ps1</code> cannot be loaded because the execution of scripts is disabled on this system.</p> </blockquote> <p>I ran this command:</p> <pre class="lang-none prettyprint-override"><code>Set-ExecutionPolicy -ExecutionPolicy Unrestricted </code></pre> <p>When I run <code>Get-ExecutionPolicy</code> from PowerShell, it returns <code>Unrestricted</code>.</p> <pre class="lang-none prettyprint-override"><code>Get-ExecutionPolicy </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>Unrestricted </code></pre> <hr /> <blockquote> <p>cd &quot;C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts&quot; powershell .\Management_Install.ps1 1</p> <p>WARNING: Running x86 PowerShell...</p> <p>File <code>C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts\Management_Install.ps1</code> cannot be loaded because the execution of scripts is disabled on this system. Please see &quot;<code>get-help about_signing</code>&quot; for more details.</p> <p>At line:1 char:25</p> <ul> <li><p><code>.\Management_Install.ps1</code> &lt;&lt;&lt;&lt; 1</p> <ul> <li><p>CategoryInfo : NotSpecified: (:) [], PSSecurityException</p> </li> <li><p>FullyQualifiedErrorId : RuntimeException</p> </li> </ul> </li> </ul> <p>C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts&gt; PAUSE</p> <p>Press any key to continue . . .</p> </blockquote> <hr /> <p>The system is <a href="https://en.wikipedia.org/wiki/Windows_Server_2008" rel="noreferrer">Windows Server 2008</a> R2.</p> <p>What am I doing wrong?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
31
bash
# PowerShell says "execution of scripts is disabled on this system." I am trying to run a `cmd` file that calls a PowerShell script from `cmd.exe`, but I am getting this error: > `Management_Install.ps1` cannot be loaded because the execution of scripts is disabled on this system. I ran this command: ``` Set-ExecutionPolicy -ExecutionPolicy Unrestricted ``` When I run `Get-ExecutionPolicy` from PowerShell, it returns `Unrestricted`. ``` Get-ExecutionPolicy ``` Output: ``` Unrestricted ``` --- > cd "C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts" > powershell .\Management_Install.ps1 1 > > WARNING: Running x86 PowerShell... > > File `C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts\Management_Install.ps1` cannot be loaded because the execution of scripts is disabled on this system. Please see "`get-help about_signing`" for more details. > > At line:1 char:25 > > - `.\Management_Install.ps1` <<<< 1 > > - CategoryInfo : NotSpecified: (:) [], PSSecurityException > - FullyQualifiedErrorId : RuntimeException > > C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts> PAUSE > > Press any key to continue . . . --- The system is [Windows Server 2008](https://en.wikipedia.org/wiki/Windows_Server_2008) R2. What am I doing wrong?
If you're using [Windows Server 2008](https://en.wikipedia.org/wiki/Windows_Server_2008) R2 then there is an *x64* and *x86* version of PowerShell both of which have to have their execution policies set. Did you set the execution policy on both hosts? As an *Administrator*, you can set the execution policy by typing this into your PowerShell window: ``` Set-ExecutionPolicy RemoteSigned ``` For more information, see *[Using the Set-ExecutionPolicy Cmdlet](https://learn.microsoft.com/powershell/module/microsoft.powershell.security/set-executionpolicy)*. When you are done, you can set the policy back to its default value with: ``` Set-ExecutionPolicy Restricted ``` You may see an error: ``` Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. To change the execution policy for the default (LocalMachine) scope, start Windows PowerShell with the "Run as administrator" option. To change the execution policy for the current user, run "Set-ExecutionPolicy -Scope CurrentUser". ``` So you may need to run the command like this (as seen in comments): ``` Set-ExecutionPolicy RemoteSigned -Scope CurrentUser ```
5410757
How can I delete all lines that contain a specific string from a text file?
2,416
2011-03-23 19:46:07
<p>How would I use sed to delete all lines in a text file that contain a specific string?</p>
2,684,037
667,236
2025-12-13 14:13:19
5,410,784
3,649
2011-03-23 19:48:46
207,248
2025-12-12 05:23:22
https://stackoverflow.com/q/5410757
https://stackoverflow.com/a/5410784
<p>To remove the line and print the output to standard out:</p> <pre><code>sed '/pattern to match/d' ./infile </code></pre> <p>To directly modify the file (it does not work with BSD sed):</p> <pre><code>sed -i '/pattern to match/d' ./infile </code></pre> <p>The same, but for BSD sed (Mac OS X and FreeBSD. It does not work with GNU sed):</p> <pre><code>sed -i '' '/pattern to match/d' ./infile </code></pre> <p>To directly modify the file (and create a backup. It works with BSD and GNU sed):</p> <pre><code>sed -i.bak '/pattern to match/d' ./infile </code></pre>
<p>To remove the line and print the output to standard out:</p> <pre><code>sed '/pattern to match/d' ./infile </code></pre> <p>To directly modify the file (it does not work with BSD sed):</p> <pre><code>sed -i '/pattern to match/d' ./infile </code></pre> <p>The same, but for BSD sed (Mac OS X and FreeBSD. It does not work with GNU sed):</p> <pre><code>sed -i '' '/pattern to match/d' ./infile </cod
390, 5282, 12189, 13401
in-place, sed, shell, text-parsing
<h1>How can I delete all lines that contain a specific string from a text file?</h1> <p>How would I use sed to delete all lines in a text file that contain a specific string?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
32
bash
# How can I delete all lines that contain a specific string from a text file? How would I use sed to delete all lines in a text file that contain a specific string?
To remove the line and print the output to standard out: ``` sed '/pattern to match/d' ./infile ``` To directly modify the file (it does not work with BSD sed): ``` sed -i '/pattern to match/d' ./infile ``` The same, but for BSD sed (Mac OS X and FreeBSD. It does not work with GNU sed): ``` sed -i '' '/pattern to match/d' ./infile ``` To directly modify the file (and create a backup. It works with BSD and GNU sed): ``` sed -i.bak '/pattern to match/d' ./infile ```
8880603
Loop through an array of strings in Bash?
2,420
2012-01-16 13:21:16
<p>I want to write a script that loops through 15 strings (array possibly?) Is that possible?</p> <pre><code>for databaseName in listOfNames then # Do something end </code></pre>
2,293,789
218,183
2025-11-19 13:31:32
8,880,633
3,621
2012-01-16 13:24:47
548,225
2025-11-19 13:31:32
https://stackoverflow.com/q/8880603
https://stackoverflow.com/a/8880633
<pre><code>## declare an array variable declare -a arr=(&quot;element 1&quot; &quot;element 2&quot; &quot;element 3&quot;) ## loop through above array (quotes are important if your elements may contain spaces) for i in &quot;${arr[@]}&quot; do echo &quot;$i&quot; # or do whatever with individual element of array done # You can access them using echo &quot;${arr[0]}&quot;, &quot;${arr[1]}&quot; also </code></pre> <p>Also works for multi-line array declaration</p> <pre><code>declare -a arr=(&quot;element1&quot; &quot;element2&quot; &quot;element3&quot; &quot;element4&quot; ) </code></pre>
<pre><code>## declare an array variable declare -a arr=(&quot;element 1&quot; &quot;element 2&quot; &quot;element 3&quot;) ## loop through above array (quotes are important if your elements may contain spaces) for i in &quot;${arr[@]}&quot; do echo &quot;$i&quot; # or do whatever with individual element of array done # You can access them using echo &quot;${arr[0]}&quot;, &quot;${arr[1]}&q
114, 387, 390
arrays, bash, shell
<h1>Loop through an array of strings in Bash?</h1> <p>I want to write a script that loops through 15 strings (array possibly?) Is that possible?</p> <pre><code>for databaseName in listOfNames then # Do something end </code></pre>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
33
bash
# Loop through an array of strings in Bash? I want to write a script that loops through 15 strings (array possibly?) Is that possible? ``` for databaseName in listOfNames then # Do something end ```
``` ## declare an array variable declare -a arr=("element 1" "element 2" "element 3") ## loop through above array (quotes are important if your elements may contain spaces) for i in "${arr[@]}" do echo "$i" # or do whatever with individual element of array done # You can access them using echo "${arr[0]}", "${arr[1]}" also ``` Also works for multi-line array declaration ``` declare -a arr=("element1" "element2" "element3" "element4" ) ```
2518127
How to reload .bashrc settings without logging out and back in again?
2,268
2010-03-25 17:58:36
<p>If I make changes to <code>.bashrc</code>, how do I reload it without logging out and back in?</p>
1,888,242
292,553
2024-09-06 14:44:36
2,518,150
3,583
2010-03-25 18:01:04
245,602
2020-10-21 14:18:32
https://stackoverflow.com/q/2518127
https://stackoverflow.com/a/2518150
<p>You can enter the long form command:</p> <pre><code>source ~/.bashrc </code></pre> <p>or you can use the shorter version of the command:</p> <pre><code>. ~/.bashrc </code></pre>
<p>You can enter the long form command:</p> <pre><code>source ~/.bashrc </code></pre> <p>or you can use the shorter version of the command:</p> <pre><code>. ~/.bashrc </code></pre>
387, 390, 391, 403, 12126
bash, profile, reload, shell, terminal
<h1>How to reload .bashrc settings without logging out and back in again?</h1> <p>If I make changes to <code>.bashrc</code>, how do I reload it without logging out and back in?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
34
bash
# How to reload .bashrc settings without logging out and back in again? If I make changes to `.bashrc`, how do I reload it without logging out and back in?
You can enter the long form command: ``` source ~/.bashrc ``` or you can use the shorter version of the command: ``` . ~/.bashrc ```
3601515
How to check if a variable is set in Bash
2,518
2010-08-30 14:54:38
<p>How do I know if a variable is set in Bash?</p> <p>For example, how do I check if the user gave the first parameter to a function?</p> <pre><code>function a { # if $1 is set ? } </code></pre>
2,489,781
260,127
2024-01-11 07:53:29
13,864,829
3,468
2012-12-13 17:04:53
1,633,643
2021-12-06 18:12:01
https://stackoverflow.com/q/3601515
https://stackoverflow.com/a/13864829
<h2>(Usually) The right way</h2> <pre><code>if [ -z ${var+x} ]; then echo &quot;var is unset&quot;; else echo &quot;var is set to '$var'&quot;; fi </code></pre> <p>where <code>${var+x}</code> is a <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02" rel="noreferrer">parameter expansion</a> which evaluates to nothing if <code>var</code> is unset, and substitutes the string <code>x</code> otherwise.</p> <h3>Quotes Digression</h3> <p>Quotes can be omitted (so we can say <code>${var+x}</code> instead of <code>&quot;${var+x}&quot;</code>) because this syntax &amp; usage guarantees this will only expand to something that does not require quotes (since it either expands to <code>x</code> (which contains no word breaks so it needs no quotes), or to nothing (which results in <code>[ -z ]</code>, which conveniently evaluates to the same value (true) that <code>[ -z &quot;&quot; ]</code> does as well)).</p> <p>However, while quotes can be safely omitted, and it was not immediately obvious to all (it wasn't even apparent to <a href="https://stackoverflow.com/users/2255628/destiny-architect">the first author of this quotes explanation</a> who is also a major Bash coder), it would sometimes be better to write the solution with quotes as <code>[ -z &quot;${var+x}&quot; ]</code>, at the very small possible cost of an O(1) speed penalty. The first author also added this as a comment next to the code using this solution giving the URL to this answer, which now also includes the explanation for why the quotes can be safely omitted.</p> <h2>(Often) The wrong way</h2> <pre><code>if [ -z &quot;$var&quot; ]; then echo &quot;var is blank&quot;; else echo &quot;var is set to '$var'&quot;; fi </code></pre> <p>This is often wrong because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if <code>var=''</code>, then the above solution will output &quot;var is blank&quot;.</p> <p>The distinction between unset and &quot;set to the empty string&quot; is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.</p> <p>The distinction may not be essential in every scenario though. In those cases <code>[ -z &quot;$var&quot; ]</code> will be just fine.</p>
<h2>(Usually) The right way</h2> <pre><code>if [ -z ${var+x} ]; then echo &quot;var is unset&quot;; else echo &quot;var is set to '$var'&quot;; fi </code></pre> <p>where <code>${var+x}</code> is a <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02" rel="noreferrer">parameter expansion</a> which evaluates to nothing if <code>var</code> is unset, and subst
276, 387, 390
bash, shell, variables
<h1>How to check if a variable is set in Bash</h1> <p>How do I know if a variable is set in Bash?</p> <p>For example, how do I check if the user gave the first parameter to a function?</p> <pre><code>function a { # if $1 is set ? } </code></pre>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
35
bash
# How to check if a variable is set in Bash How do I know if a variable is set in Bash? For example, how do I check if the user gave the first parameter to a function? ``` function a { # if $1 is set ? } ```
## (Usually) The right way ``` if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fi ``` where `${var+x}` is a [parameter expansion](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02) which evaluates to nothing if `var` is unset, and substitutes the string `x` otherwise. ### Quotes Digression Quotes can be omitted (so we can say `${var+x}` instead of `"${var+x}"`) because this syntax & usage guarantees this will only expand to something that does not require quotes (since it either expands to `x` (which contains no word breaks so it needs no quotes), or to nothing (which results in `[ -z ]`, which conveniently evaluates to the same value (true) that `[ -z "" ]` does as well)). However, while quotes can be safely omitted, and it was not immediately obvious to all (it wasn't even apparent to [the first author of this quotes explanation](https://stackoverflow.com/users/2255628/destiny-architect) who is also a major Bash coder), it would sometimes be better to write the solution with quotes as `[ -z "${var+x}" ]`, at the very small possible cost of an O(1) speed penalty. The first author also added this as a comment next to the code using this solution giving the URL to this answer, which now also includes the explanation for why the quotes can be safely omitted. ## (Often) The wrong way ``` if [ -z "$var" ]; then echo "var is blank"; else echo "var is set to '$var'"; fi ``` This is often wrong because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if `var=''`, then the above solution will output "var is blank". The distinction between unset and "set to the empty string" is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties. The distinction may not be essential in every scenario though. In those cases `[ -z "$var" ]` will be just fine.
6482377
Check existence of input argument in a Bash shell script
2,049
2011-06-26 05:49:21
<p>I need to check the existence of an input argument. I have the following script</p> <pre><code>if [ "$1" -gt "-1" ] then echo hi fi </code></pre> <p>I get</p> <pre><code>[: : integer expression expected </code></pre> <p>How do I check the input argument1 first to see if it exists?</p>
2,126,764
775,187
2024-06-03 04:03:01
6,482,403
3,395
2011-06-26 05:55:41
702,361
2021-01-28 08:38:46
https://stackoverflow.com/q/6482377
https://stackoverflow.com/a/6482403
<p>It is:</p> <pre class="lang-bash prettyprint-override"><code>if [ $# -eq 0 ] then echo &quot;No arguments supplied&quot; fi </code></pre> <p>The <code>$#</code> variable will tell you the number of input arguments the script was passed.</p> <p>Or you can check if an argument is an empty string or not like:</p> <pre><code>if [ -z &quot;$1&quot; ] then echo &quot;No argument supplied&quot; fi </code></pre> <p>The <code>-z</code> switch will test if the expansion of <code>&quot;$1&quot;</code> is a null string or not. If it is a null string then the body is executed.</p>
<p>It is:</p> <pre class="lang-bash prettyprint-override"><code>if [ $# -eq 0 ] then echo &quot;No arguments supplied&quot; fi </code></pre> <p>The <code>$#</code> variable will tell you the number of input arguments the script was passed.</p> <p>Or you can check if an argument is an empty string or not like:</p> <pre><code>if [ -z &quot;$1&quot; ] then echo &quot;No argument supplied&
387, 390
bash, shell
<h1>Check existence of input argument in a Bash shell script</h1> <p>I need to check the existence of an input argument. I have the following script</p> <pre><code>if [ "$1" -gt "-1" ] then echo hi fi </code></pre> <p>I get</p> <pre><code>[: : integer expression expected </code></pre> <p>How do I check the input argument1 first to see if it exists?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
36
bash
# Check existence of input argument in a Bash shell script I need to check the existence of an input argument. I have the following script ``` if [ "$1" -gt "-1" ] then echo hi fi ``` I get ``` [: : integer expression expected ``` How do I check the input argument1 first to see if it exists?
It is: ``` if [ $# -eq 0 ] then echo "No arguments supplied" fi ``` The `$#` variable will tell you the number of input arguments the script was passed. Or you can check if an argument is an empty string or not like: ``` if [ -z "$1" ] then echo "No argument supplied" fi ``` The `-z` switch will test if the expansion of `"$1"` is a null string or not. If it is a null string then the body is executed.
1358540
How can I count all the lines of code in a directory recursively?
2,114
2009-08-31 17:42:20
<p>We've got a PHP application and want to count all the lines of code under a specific directory and its subdirectories.</p> <p>We don't need to ignore comments, as we're just trying to get a rough idea.</p> <pre><code>wc -l *.php </code></pre> <p>That command works great for a given directory, but it ignores subdirectories. I was thinking the following comment might work, but it is returning 74, which is definitely not the case...</p> <pre><code>find . -name '*.php' | wc -l </code></pre> <p>What's the correct syntax to feed in all the files from a directory resursively?</p>
1,285,868
77,413
2024-08-01 03:57:59
1,358,573
3,342
2009-08-31 17:50:12
76,794
2021-05-27 09:50:00
https://stackoverflow.com/q/1358540
https://stackoverflow.com/a/1358573
<p><strong>Try:</strong></p> <pre><code>find . -name '*.php' | xargs wc -l </code></pre> <p>or (when file names include special characters such as spaces)</p> <pre><code>find . -name '*.php' | sed 's/.*/&quot;&amp;&quot;/' | xargs wc -l </code></pre> <p><strong><a href="https://dwheeler.com/sloccount/" rel="noreferrer">The SLOCCount tool</a></strong> may help as well.</p> <p>It will give an accurate source lines of code count for whatever hierarchy you point it at, as well as some additional stats.</p> <p><strong>Sorted output:</strong></p> <p><code>find . -name '*.php' | xargs wc -l | sort -nr</code></p>
<p><strong>Try:</strong></p> <pre><code>find . -name '*.php' | xargs wc -l </code></pre> <p>or (when file names include special characters such as spaces)</p> <pre><code>find . -name '*.php' | sed 's/.*/&quot;&amp;&quot;/' | xargs wc -l </code></pre> <p><strong><a href="https://dwheeler.com/sloccount/" rel="noreferrer">The SLOCCount tool</a></strong> may help as well.</p> <p>It will give an accur
387, 390
bash, shell
<h1>How can I count all the lines of code in a directory recursively?</h1> <p>We've got a PHP application and want to count all the lines of code under a specific directory and its subdirectories.</p> <p>We don't need to ignore comments, as we're just trying to get a rough idea.</p> <pre><code>wc -l *.php </code></pre> <p>That command works great for a given directory, but it ignores subdirectories. I was thinking the following comment might work, but it is returning 74, which is definitely not the case...</p> <pre><code>find . -name '*.php' | wc -l </code></pre> <p>What's the correct syntax to feed in all the files from a directory resursively?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
37
bash
# How can I count all the lines of code in a directory recursively? We've got a PHP application and want to count all the lines of code under a specific directory and its subdirectories. We don't need to ignore comments, as we're just trying to get a rough idea. ``` wc -l *.php ``` That command works great for a given directory, but it ignores subdirectories. I was thinking the following comment might work, but it is returning 74, which is definitely not the case... ``` find . -name '*.php' | wc -l ``` What's the correct syntax to feed in all the files from a directory resursively?
**Try:** ``` find . -name '*.php' | xargs wc -l ``` or (when file names include special characters such as spaces) ``` find . -name '*.php' | sed 's/.*/"&"/' | xargs wc -l ``` **[The SLOCCount tool](https://dwheeler.com/sloccount/)** may help as well. It will give an accurate source lines of code count for whatever hierarchy you point it at, as well as some additional stats. **Sorted output:** `find . -name '*.php' | xargs wc -l | sort -nr`
4651437
How do I set a variable to the output of a command in Bash?
2,507
2011-01-10 20:58:02
<p>I have a pretty simple script that is something like the following:</p> <pre><code>#!/bin/bash VAR1="$1" MOREF='sudo run command against $VAR1 | grep name | cut -c7-' echo $MOREF </code></pre> <p>When I run this script from the command line and pass it the arguments, I am not getting any output. However, when I run the commands contained within the <code>$MOREF</code> variable, I am able to get output.</p> <p>How can one take the results of a command that needs to be run within a script, save it to a variable, and then output that variable on the screen?</p>
3,105,029
570,402
2025-09-19 06:29:46
4,651,495
3,283
2011-01-10 21:04:18
8,454
2024-08-26 16:01:57
https://stackoverflow.com/q/4651437
https://stackoverflow.com/a/4651495
<p>In addition to backticks <code>`command`</code>, <a href="http://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution" rel="noreferrer">command substitution</a> can be done with <code>$(command)</code> or <code>&quot;$(command)&quot;</code>, which I find easier to read, and allows for nesting.</p> <pre><code>OUTPUT=&quot;$(ls -1)&quot; echo &quot;${OUTPUT}&quot; MULTILINE=&quot;$(ls \ -1)&quot; echo &quot;${MULTILINE}&quot; </code></pre> <p>Quoting (<code>&quot;</code>) does matter to preserve <strong>multi-line variable values</strong> and it is safer to use with whitespace and special characters such as (<code>*</code>) and therefore advised; it is, however, optional on the right-hand side of an assignment when <a href="https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Shell-Parameters" rel="noreferrer">word splitting is not performed</a>, so <code>OUTPUT=$(ls -1)</code> would work fine.</p>
<p>In addition to backticks <code>`command`</code>, <a href="http://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution" rel="noreferrer">command substitution</a> can be done with <code>$(command)</code> or <code>&quot;$(command)&quot;</code>, which I find easier to read, and allows for nesting.</p> <pre><code>OUTPUT=&quot;$(ls -1)&quot; echo &quot;${OUTPUT}&quot; MULTILINE=&quot;$
387, 390, 1231
bash, command-line, shell
<h1>How do I set a variable to the output of a command in Bash?</h1> <p>I have a pretty simple script that is something like the following:</p> <pre><code>#!/bin/bash VAR1="$1" MOREF='sudo run command against $VAR1 | grep name | cut -c7-' echo $MOREF </code></pre> <p>When I run this script from the command line and pass it the arguments, I am not getting any output. However, when I run the commands contained within the <code>$MOREF</code> variable, I am able to get output.</p> <p>How can one take the results of a command that needs to be run within a script, save it to a variable, and then output that variable on the screen?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
38
bash
# How do I set a variable to the output of a command in Bash? I have a pretty simple script that is something like the following: ``` #!/bin/bash VAR1="$1" MOREF='sudo run command against $VAR1 | grep name | cut -c7-' echo $MOREF ``` When I run this script from the command line and pass it the arguments, I am not getting any output. However, when I run the commands contained within the `$MOREF` variable, I am able to get output. How can one take the results of a command that needs to be run within a script, save it to a variable, and then output that variable on the screen?
In addition to backticks `` `command` ``, [command substitution](http://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution) can be done with `$(command)` or `"$(command)"`, which I find easier to read, and allows for nesting. ``` OUTPUT="$(ls -1)" echo "${OUTPUT}" MULTILINE="$(ls \ -1)" echo "${MULTILINE}" ``` Quoting (`"`) does matter to preserve **multi-line variable values** and it is safer to use with whitespace and special characters such as (`*`) and therefore advised; it is, however, optional on the right-hand side of an assignment when [word splitting is not performed](https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Shell-Parameters), so `OUTPUT=$(ls -1)` would work fine.
2264428
How to convert a string to lower case in Bash
1,893
2010-02-15 07:02:56
<p>Is there a way in <a href="/questions/tagged/bash" class="post-tag" title="show questions tagged &#39;bash&#39;" rel="tag">bash</a> to convert a string into a lower case string?</p> <p>For example, if I have:</p> <pre><code>a="Hi all" </code></pre> <p>I want to convert it to:</p> <pre><code>"hi all" </code></pre>
1,602,361
266,008
2024-10-02 06:03:31
2,264,537
3,129
2010-02-15 07:43:20
131,527
2024-10-02 06:03:31
https://stackoverflow.com/q/2264428
https://stackoverflow.com/a/2264537
<p>There are various ways:</p> <h3><a href="https://wikipedia.org/wiki/POSIX" rel="noreferrer">POSIX standard</a></h3> <h4><a href="https://wikipedia.org/wiki/Tr_%28Unix%29" rel="noreferrer">tr</a></h4> <pre><code>$ echo &quot;$a&quot; | tr '[:upper:]' '[:lower:]' hi all </code></pre> <h4><a href="https://wikipedia.org/wiki/AWK" rel="noreferrer">AWK</a></h4> <pre><code>$ echo &quot;$a&quot; | awk '{print tolower($0)}' hi all </code></pre> <h2>Non-POSIX</h2> <p>You may run into portability issues with the following examples:</p> <h4><a href="https://wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash 4.0</a></h4> <pre><code>$ echo &quot;${a,,}&quot; hi all </code></pre> <h4><a href="https://wikipedia.org/wiki/Sed" rel="noreferrer">sed</a></h4> <pre><code>$ echo &quot;$a&quot; | sed -e 's/\(.*\)/\L\1/' hi all # this also works: $ sed -e 's/\(.*\)/\L\1/' &lt;&lt;&lt; &quot;$a&quot; hi all </code></pre> <h4><a href="https://wikipedia.org/wiki/Perl" rel="noreferrer">Perl</a></h4> <pre><code>$ echo &quot;$a&quot; | perl -ne 'print lc' hi all </code></pre> <h4><a href="https://wikipedia.org/wiki/Bash_%28Unix_shell%29" rel="noreferrer">Bash</a></h4> <pre><code>lc(){ case &quot;$1&quot; in [A-Z]) n=$(printf &quot;%d&quot; &quot;'$1&quot;) n=$((n+32)) printf \\$(printf &quot;%o&quot; &quot;$n&quot;) ;; *) printf &quot;%s&quot; &quot;$1&quot; ;; esac } word=&quot;I Love Bash&quot; for((i=0;i&lt;${#word};i++)) do ch=&quot;${word:$i:1}&quot; lc &quot;$ch&quot; done </code></pre> <p>Note: YMMV on this one. Doesn't work for me (GNU bash version 4.2.46 and 4.0.33 (and same behaviour 2.05b.0 but <code>nocasematch</code> is not implemented)) even with using <code>shopt -u nocasematch;</code>. Unsetting that <code>nocasematch</code> causes <code>[[ &quot;fooBaR&quot; == &quot;FOObar&quot; ]]</code> to match OK BUT inside case weirdly <code>[b-z]</code> are incorrectly matched by <code>[A-Z]</code>. Bash is confused by the double-negative (&quot;unsetting nocasematch&quot;)! :-)</p>
<p>There are various ways:</p> <h3><a href="https://wikipedia.org/wiki/POSIX" rel="noreferrer">POSIX standard</a></h3> <h4><a href="https://wikipedia.org/wiki/Tr_%28Unix%29" rel="noreferrer">tr</a></h4> <pre><code>$ echo &quot;$a&quot; | tr '[:upper:]' '[:lower:]' hi all </code></pre> <h4><a href="https://wikipedia.org/wiki/AWK" rel="noreferrer">AWK</a></h4> <pre><code>$ echo &quot;$a&quot; | awk
139, 387, 390, 9848
bash, lowercase, shell, string
<h1>How to convert a string to lower case in Bash</h1> <p>Is there a way in <a href="/questions/tagged/bash" class="post-tag" title="show questions tagged &#39;bash&#39;" rel="tag">bash</a> to convert a string into a lower case string?</p> <p>For example, if I have:</p> <pre><code>a="Hi all" </code></pre> <p>I want to convert it to:</p> <pre><code>"hi all" </code></pre>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
39
bash
# How to convert a string to lower case in Bash Is there a way in [bash](/questions/tagged/bash "show questions tagged 'bash'") to convert a string into a lower case string? For example, if I have: ``` a="Hi all" ``` I want to convert it to: ``` "hi all" ```
There are various ways: ### [POSIX standard](https://wikipedia.org/wiki/POSIX) #### [tr](https://wikipedia.org/wiki/Tr_%28Unix%29) ``` $ echo "$a" | tr '[:upper:]' '[:lower:]' hi all ``` #### [AWK](https://wikipedia.org/wiki/AWK) ``` $ echo "$a" | awk '{print tolower($0)}' hi all ``` ## Non-POSIX You may run into portability issues with the following examples: #### [Bash 4.0](https://wikipedia.org/wiki/Bash_%28Unix_shell%29) ``` $ echo "${a,,}" hi all ``` #### [sed](https://wikipedia.org/wiki/Sed) ``` $ echo "$a" | sed -e 's/\(.*\)/\L\1/' hi all # this also works: $ sed -e 's/\(.*\)/\L\1/' <<< "$a" hi all ``` #### [Perl](https://wikipedia.org/wiki/Perl) ``` $ echo "$a" | perl -ne 'print lc' hi all ``` #### [Bash](https://wikipedia.org/wiki/Bash_%28Unix_shell%29) ``` lc(){ case "$1" in [A-Z]) n=$(printf "%d" "'$1") n=$((n+32)) printf \\$(printf "%o" "$n") ;; *) printf "%s" "$1" ;; esac } word="I Love Bash" for((i=0;i<${#word};i++)) do ch="${word:$i:1}" lc "$ch" done ``` Note: YMMV on this one. Doesn't work for me (GNU bash version 4.2.46 and 4.0.33 (and same behaviour 2.05b.0 but `nocasematch` is not implemented)) even with using `shopt -u nocasematch;`. Unsetting that `nocasematch` causes `[[ "fooBaR" == "FOObar" ]]` to match OK BUT inside case weirdly `[b-z]` are incorrectly matched by `[A-Z]`. Bash is confused by the double-negative ("unsetting nocasematch")! :-)
1521462
Looping through the content of a file in Bash
2,202
2009-10-05 17:52:54
<p>How do I iterate through each line of a text file with <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)" rel="noreferrer">Bash</a>?</p> <p>With this script:</p> <pre><code>echo "Start!" for p in (peptides.txt) do echo "${p}" done </code></pre> <p>I get this output on the screen:</p> <pre><code>Start! ./runPep.sh: line 3: syntax error near unexpected token `(' ./runPep.sh: line 3: `for p in (peptides.txt)' </code></pre> <p>(Later I want to do something more complicated with <code>$p</code> than just output to the screen.)</p> <hr> <p>The environment variable <strong>SHELL</strong> is (from env):</p> <pre><code>SHELL=/bin/bash </code></pre> <p><code>/bin/bash --version</code> output:</p> <pre><code>GNU bash, version 3.1.17(1)-release (x86_64-suse-linux-gnu) Copyright (C) 2005 Free Software Foundation, Inc. </code></pre> <p><code>cat /proc/version</code> output:</p> <pre><code>Linux version 2.6.18.2-34-default (geeko@buildhost) (gcc version 4.1.2 20061115 (prerelease) (SUSE Linux)) #1 SMP Mon Nov 27 11:46:27 UTC 2006 </code></pre> <p>The file peptides.txt contains:</p> <pre><code>RKEKNVQ IPKKLLQK QYFHQLEKMNVK IPKKLLQK GDLSTALEVAIDCYEK QYFHQLEKMNVKIPENIYR RKEKNVQ VLAKHGKLQDAIN ILGFMK LEDVALQILL </code></pre>
3,042,183
63,550
2025-12-03 13:38:30
1,521,498
3,056
2009-10-05 18:00:20
6,918
2019-10-31 17:28:04
https://stackoverflow.com/q/1521462
https://stackoverflow.com/a/1521498
<p>One way to do it is:</p> <pre><code>while read p; do echo "$p" done &lt;peptides.txt </code></pre> <p>As pointed out in the comments, this has the side effects of trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it's missing a terminating linefeed. If these are concerns, you can do:</p> <pre><code>while IFS="" read -r p || [ -n "$p" ] do printf '%s\n' "$p" done &lt; peptides.txt </code></pre> <hr> <p>Exceptionally, if the <a href="https://unix.stackexchange.com/questions/107800/using-while-loop-to-ssh-to-multiple-servers">loop body may read from standard input</a>, you can open the file using a different file descriptor:</p> <pre><code>while read -u 10 p; do ... done 10&lt;peptides.txt </code></pre> <p>Here, 10 is just an arbitrary number (different from 0, 1, 2).</p>
<p>One way to do it is:</p> <pre><code>while read p; do echo "$p" done &lt;peptides.txt </code></pre> <p>As pointed out in the comments, this has the side effects of trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it's missing a terminating linefeed. If these are concerns, you can do:</p> <pre><code>while IFS="" read -r p || [ -n "$p" ] do printf
34, 58, 345, 387, 10327
bash, io, linux, sh, unix
<h1>Looping through the content of a file in Bash</h1> <p>How do I iterate through each line of a text file with <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)" rel="noreferrer">Bash</a>?</p> <p>With this script:</p> <pre><code>echo "Start!" for p in (peptides.txt) do echo "${p}" done </code></pre> <p>I get this output on the screen:</p> <pre><code>Start! ./runPep.sh: line 3: syntax error near unexpected token `(' ./runPep.sh: line 3: `for p in (peptides.txt)' </code></pre> <p>(Later I want to do something more complicated with <code>$p</code> than just output to the screen.)</p> <hr> <p>The environment variable <strong>SHELL</strong> is (from env):</p> <pre><code>SHELL=/bin/bash </code></pre> <p><code>/bin/bash --version</code> output:</p> <pre><code>GNU bash, version 3.1.17(1)-release (x86_64-suse-linux-gnu) Copyright (C) 2005 Free Software Foundation, Inc. </code></pre> <p><code>cat /proc/version</code> output:</p> <pre><code>Linux version 2.6.18.2-34-default (geeko@buildhost) (gcc version 4.1.2 20061115 (prerelease) (SUSE Linux)) #1 SMP Mon Nov 27 11:46:27 UTC 2006 </code></pre> <p>The file peptides.txt contains:</p> <pre><code>RKEKNVQ IPKKLLQK QYFHQLEKMNVK IPKKLLQK GDLSTALEVAIDCYEK QYFHQLEKMNVKIPENIYR RKEKNVQ VLAKHGKLQDAIN ILGFMK LEDVALQILL </code></pre>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
40
bash
# Looping through the content of a file in Bash How do I iterate through each line of a text file with [Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell))? With this script: ``` echo "Start!" for p in (peptides.txt) do echo "${p}" done ``` I get this output on the screen: ``` Start! ./runPep.sh: line 3: syntax error near unexpected token `(' ./runPep.sh: line 3: `for p in (peptides.txt)' ``` (Later I want to do something more complicated with `$p` than just output to the screen.) --- The environment variable **SHELL** is (from env): ``` SHELL=/bin/bash ``` `/bin/bash --version` output: ``` GNU bash, version 3.1.17(1)-release (x86_64-suse-linux-gnu) Copyright (C) 2005 Free Software Foundation, Inc. ``` `cat /proc/version` output: ``` Linux version 2.6.18.2-34-default (geeko@buildhost) (gcc version 4.1.2 20061115 (prerelease) (SUSE Linux)) #1 SMP Mon Nov 27 11:46:27 UTC 2006 ``` The file peptides.txt contains: ``` RKEKNVQ IPKKLLQK QYFHQLEKMNVK IPKKLLQK GDLSTALEVAIDCYEK QYFHQLEKMNVKIPENIYR RKEKNVQ VLAKHGKLQDAIN ILGFMK LEDVALQILL ```
One way to do it is: ``` while read p; do echo "$p" done <peptides.txt ``` As pointed out in the comments, this has the side effects of trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it's missing a terminating linefeed. If these are concerns, you can do: ``` while IFS="" read -r p || [ -n "$p" ] do printf '%s\n' "$p" done < peptides.txt ``` --- Exceptionally, if the [loop body may read from standard input](https://unix.stackexchange.com/questions/107800/using-while-loop-to-ssh-to-multiple-servers), you can open the file using a different file descriptor: ``` while read -u 10 p; do ... done 10<peptides.txt ``` Here, 10 is just an arbitrary number (different from 0, 1, 2).
7131670
Make a Bash alias that takes a parameter?
1,899
2011-08-20 12:11:41
<p>I used to use CShell (<a href="/questions/tagged/csh" class="post-tag" title="show questions tagged &#39;csh&#39;" rel="tag">csh</a>), which lets you make an alias that takes a parameter. The notation was something like</p> <pre><code>alias junk="mv \\!* ~/.Trash" </code></pre> <p>In Bash, this does not seem to work. Given that Bash has a multitude of useful features, I would assume that this one has been implemented but I am wondering how.</p>
997,593
902,361
2025-02-04 10:19:27
7,131,683
2,996
2011-08-20 12:15:04
203,454
2019-04-11 08:24:04
https://stackoverflow.com/q/7131670
https://stackoverflow.com/a/7131683
<p>Bash alias does not directly accept parameters. You will have to create a function.</p> <p><code>alias</code> does not accept parameters but a function can be called just like an alias. For example:</p> <pre><code>myfunction() { #do things with parameters like $1 such as mv "$1" "$1.bak" cp "$2" "$1" } myfunction old.conf new.conf #calls `myfunction` </code></pre> <p>By the way, Bash functions defined in your <code>.bashrc</code> and other files are available as commands within your shell. So for instance you can call the earlier function like this </p> <pre><code>$ myfunction original.conf my.conf </code></pre>
<p>Bash alias does not directly accept parameters. You will have to create a function.</p> <p><code>alias</code> does not accept parameters but a function can be called just like an alias. For example:</p> <pre><code>myfunction() { #do things with parameters like $1 such as mv "$1" "$1.bak" cp "$2" "$1" } myfunction old.conf new.conf #calls `myfunction` </code></pre> <p>By the way
387, 1448
alias, bash
<h1>Make a Bash alias that takes a parameter?</h1> <p>I used to use CShell (<a href="/questions/tagged/csh" class="post-tag" title="show questions tagged &#39;csh&#39;" rel="tag">csh</a>), which lets you make an alias that takes a parameter. The notation was something like</p> <pre><code>alias junk="mv \\!* ~/.Trash" </code></pre> <p>In Bash, this does not seem to work. Given that Bash has a multitude of useful features, I would assume that this one has been implemented but I am wondering how.</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
41
bash
# Make a Bash alias that takes a parameter? I used to use CShell ([csh](/questions/tagged/csh "show questions tagged 'csh'")), which lets you make an alias that takes a parameter. The notation was something like ``` alias junk="mv \\!* ~/.Trash" ``` In Bash, this does not seem to work. Given that Bash has a multitude of useful features, I would assume that this one has been implemented but I am wondering how.
Bash alias does not directly accept parameters. You will have to create a function. `alias` does not accept parameters but a function can be called just like an alias. For example: ``` myfunction() { #do things with parameters like $1 such as mv "$1" "$1.bak" cp "$2" "$1" } myfunction old.conf new.conf #calls `myfunction` ``` By the way, Bash functions defined in your `.bashrc` and other files are available as commands within your shell. So for instance you can call the earlier function like this ``` $ myfunction original.conf my.conf ```
876239
How to redirect and append both standard output and standard error to a file with Bash
2,110
2009-05-18 04:19:45
<p>To redirect <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29" rel="noreferrer">standard output</a> to a truncated file in Bash, I know to use:</p> <pre><code>cmd &gt; file.txt </code></pre> <p>To redirect standard output in Bash, appending to a file, I know to use:</p> <pre><code>cmd &gt;&gt; file.txt </code></pre> <p>To redirect both standard output and <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)" rel="noreferrer">standard error</a> to a truncated file, I know to use:</p> <pre><code>cmd &amp;&gt; file.txt </code></pre> <p>How do I redirect both standard output and standard error appending to a file? <code>cmd &amp;&gt;&gt; file.txt</code> did not work for me.</p>
1,166,671
63,051
2023-11-19 09:42:16
876,242
2,670
2009-05-18 04:23:16
95,810
2017-03-09 14:55:58
https://stackoverflow.com/q/876239
https://stackoverflow.com/a/876242
<pre><code>cmd &gt;&gt;file.txt 2&gt;&amp;1 </code></pre> <p>Bash executes the redirects from left to right as follows:</p> <ol> <li><code>&gt;&gt;file.txt</code>: Open <code>file.txt</code> in append mode and redirect <code>stdout</code> there.</li> <li><code>2&gt;&amp;1</code>: Redirect <code>stderr</code> to <em>"where <code>stdout</code> is currently going"</em>. In this case, that is a file opened in append mode. In other words, the <code>&amp;1</code> reuses the file descriptor which <code>stdout</code> currently uses.</li> </ol>
<pre><code>cmd &gt;&gt;file.txt 2&gt;&amp;1 </code></pre> <p>Bash executes the redirects from left to right as follows:</p> <ol> <li><code>&gt;&gt;file.txt</code>: Open <code>file.txt</code> in append mode and redirect <code>stdout</code> there.</li> <li><code>2&gt;&amp;1</code>: Redirect <code>stderr</code> to <em>"where <code>stdout</code> is currently going"</em>. In this case, that is a file
387, 4867, 6051, 19156, 26698
append, bash, io-redirection, stderr, stdout
<h1>How to redirect and append both standard output and standard error to a file with Bash</h1> <p>To redirect <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29" rel="noreferrer">standard output</a> to a truncated file in Bash, I know to use:</p> <pre><code>cmd &gt; file.txt </code></pre> <p>To redirect standard output in Bash, appending to a file, I know to use:</p> <pre><code>cmd &gt;&gt; file.txt </code></pre> <p>To redirect both standard output and <a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)" rel="noreferrer">standard error</a> to a truncated file, I know to use:</p> <pre><code>cmd &amp;&gt; file.txt </code></pre> <p>How do I redirect both standard output and standard error appending to a file? <code>cmd &amp;&gt;&gt; file.txt</code> did not work for me.</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
42
bash
# How to redirect and append both standard output and standard error to a file with Bash To redirect [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29) to a truncated file in Bash, I know to use: ``` cmd > file.txt ``` To redirect standard output in Bash, appending to a file, I know to use: ``` cmd >> file.txt ``` To redirect both standard output and [standard error](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) to a truncated file, I know to use: ``` cmd &> file.txt ``` How do I redirect both standard output and standard error appending to a file? `cmd &>> file.txt` did not work for me.
``` cmd >>file.txt 2>&1 ``` Bash executes the redirects from left to right as follows: 1. `>>file.txt`: Open `file.txt` in append mode and redirect `stdout` there. 2. `2>&1`: Redirect `stderr` to *"where `stdout` is currently going"*. In this case, that is a file opened in append mode. In other words, the `&1` reuses the file descriptor which `stdout` currently uses.
2013547
Assigning default values to shell variables with a single command in bash
1,467
2010-01-06 14:29:31
<p>I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.:</p> <pre><code>if [ -z "${VARIABLE}" ]; then FOO='default' else FOO=${VARIABLE} fi </code></pre> <p>I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.:</p> <pre><code>FOO=${ ${VARIABLE} : 'default' } </code></pre> <p>(though I know that won't work...)</p> <p>Am I crazy, or does something like that exist?</p>
984,074
87,408
2025-12-05 15:39:20
2,013,589
2,619
2010-01-06 14:36:56
241,774
2024-10-17 09:37:22
https://stackoverflow.com/q/2013547
https://stackoverflow.com/a/2013589
<p>Very close to what you posted, actually. You can use something called <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">Bash parameter expansion</a> to accomplish this.</p> <p>To get the assigned value, or <code>default</code> if it's missing:</p> <pre><code>FOO=&quot;${VARIABLE:-default}&quot; # FOO will be assigned 'default' value if VARIABLE not set or null. # The value of VARIABLE remains untouched. </code></pre> <p>To do the same, as well as assign <code>default</code> to <code>VARIABLE</code>:</p> <pre><code>FOO=&quot;${VARIABLE:=default}&quot; # If VARIABLE not set or null, set its value to 'default'. # Then that value will be assigned to FOO </code></pre>
<p>Very close to what you posted, actually. You can use something called <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html" rel="noreferrer">Bash parameter expansion</a> to accomplish this.</p> <p>To get the assigned value, or <code>default</code> if it's missing:</p> <pre><code>FOO=&quot;${VARIABLE:-default}&quot; # FOO will be assigned 'default' value if
387, 390
bash, shell
<h1>Assigning default values to shell variables with a single command in bash</h1> <p>I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.:</p> <pre><code>if [ -z "${VARIABLE}" ]; then FOO='default' else FOO=${VARIABLE} fi </code></pre> <p>I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.:</p> <pre><code>FOO=${ ${VARIABLE} : 'default' } </code></pre> <p>(though I know that won't work...)</p> <p>Am I crazy, or does something like that exist?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
43
bash
# Assigning default values to shell variables with a single command in bash I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.: ``` if [ -z "${VARIABLE}" ]; then FOO='default' else FOO=${VARIABLE} fi ``` I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.: ``` FOO=${ ${VARIABLE} : 'default' } ``` (though I know that won't work...) Am I crazy, or does something like that exist?
Very close to what you posted, actually. You can use something called [Bash parameter expansion](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) to accomplish this. To get the assigned value, or `default` if it's missing: ``` FOO="${VARIABLE:-default}" # FOO will be assigned 'default' value if VARIABLE not set or null. # The value of VARIABLE remains untouched. ``` To do the same, as well as assign `default` to `VARIABLE`: ``` FOO="${VARIABLE:=default}" # If VARIABLE not set or null, set its value to 'default'. # Then that value will be assigned to FOO ```
3137094
Count number of lines in a non binary file (Like a CSV or a TXT) file in terminal
1,458
2010-06-29 00:31:31
<p>I have a text file, and I like to know the total number of line withou opening it. My document is like these, and I want to know how many lines actually...</p> <pre><code>09:16:39 AM all 2.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 94.00 09:16:40 AM all 5.00 0.00 0.00 4.00 0.00 0.00 0.00 0.00 91.00 09:16:41 AM all 0.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 96.00 09:16:42 AM all 3.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 96.00 09:16:43 AM all 0.00 0.00 1.00 0.00 1.00 0.00 0.00 0.00 98.00 09:16:44 AM all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:16:45 AM all 2.00 0.00 6.00 0.00 0.00 0.00 0.00 0.00 92.00 </code></pre> <p>Is there a way to count in Linux Terminal?</p>
1,924,090
368,453
2024-09-13 12:33:01
3,137,099
2,601
2010-06-29 00:33:38
85,509
2015-04-29 19:27:45
https://stackoverflow.com/q/3137094
https://stackoverflow.com/a/3137099
<p>Use <code>wc</code>:</p> <pre><code>wc -l &lt;filename&gt; </code></pre> <p>This will output the number of lines in <code>&lt;filename&gt;</code>:</p> <pre><code>$ wc -l /dir/file.txt 3272485 /dir/file.txt </code></pre> <p>Or, to omit the <code>&lt;filename&gt;</code> from the result use <code>wc -l &lt; &lt;filename&gt;</code>:</p> <pre><code>$ wc -l &lt; /dir/file.txt 3272485 </code></pre> <p>You can also pipe data to <code>wc</code> as well:</p> <pre><code>$ cat /dir/file.txt | wc -l 3272485 $ curl yahoo.com --silent | wc -l 63 </code></pre>
<p>Use <code>wc</code>:</p> <pre><code>wc -l &lt;filename&gt; </code></pre> <p>This will output the number of lines in <code>&lt;filename&gt;</code>:</p> <pre><code>$ wc -l /dir/file.txt 3272485 /dir/file.txt </code></pre> <p>Or, to omit the <code>&lt;filename&gt;</code> from the result use <code>wc -l &lt; &lt;filename&gt;</code>:</p> <pre><code>$ wc -l &lt; /dir/file.txt 3272485 </code></pr
58, 387, 531, 1231
bash, command-line, linux, scripting
<h1>Count number of lines in a non binary file (Like a CSV or a TXT) file in terminal</h1> <p>I have a text file, and I like to know the total number of line withou opening it. My document is like these, and I want to know how many lines actually...</p> <pre><code>09:16:39 AM all 2.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 94.00 09:16:40 AM all 5.00 0.00 0.00 4.00 0.00 0.00 0.00 0.00 91.00 09:16:41 AM all 0.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 96.00 09:16:42 AM all 3.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 96.00 09:16:43 AM all 0.00 0.00 1.00 0.00 1.00 0.00 0.00 0.00 98.00 09:16:44 AM all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:16:45 AM all 2.00 0.00 6.00 0.00 0.00 0.00 0.00 0.00 92.00 </code></pre> <p>Is there a way to count in Linux Terminal?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
44
bash
# Count number of lines in a non binary file (Like a CSV or a TXT) file in terminal I have a text file, and I like to know the total number of line withou opening it. My document is like these, and I want to know how many lines actually... ``` 09:16:39 AM all 2.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 94.00 09:16:40 AM all 5.00 0.00 0.00 4.00 0.00 0.00 0.00 0.00 91.00 09:16:41 AM all 0.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 96.00 09:16:42 AM all 3.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 96.00 09:16:43 AM all 0.00 0.00 1.00 0.00 1.00 0.00 0.00 0.00 98.00 09:16:44 AM all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:16:45 AM all 2.00 0.00 6.00 0.00 0.00 0.00 0.00 0.00 92.00 ``` Is there a way to count in Linux Terminal?
Use `wc`: ``` wc -l <filename> ``` This will output the number of lines in `<filename>`: ``` $ wc -l /dir/file.txt 3272485 /dir/file.txt ``` Or, to omit the `<filename>` from the result use `wc -l < <filename>`: ``` $ wc -l < /dir/file.txt 3272485 ``` You can also pipe data to `wc` as well: ``` $ cat /dir/file.txt | wc -l 3272485 $ curl yahoo.com --silent | wc -l 63 ```
169511
How do I iterate over a range of numbers defined by variables in Bash?
2,273
2008-10-04 01:38:43
<p>How do I iterate over a range of numbers in Bash when the range is given by a variable?</p> <p>I know I can do this (called &quot;sequence expression&quot; in the Bash <a href="http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion" rel="noreferrer">documentation</a>):</p> <pre><code>for i in {1..5}; do echo $i; done </code></pre> <p>Which gives:</p> <blockquote> <p>1 <br/> 2 <br/> 3 <br/> 4 <br/> 5</p> </blockquote> <p>Yet, how can I replace either of the range endpoints with a variable? This doesn't work:</p> <pre><code>END=5 for i in {1..$END}; do echo $i; done </code></pre> <p>Which prints:</p> <blockquote> <p>{1..5}</p> </blockquote>
1,926,914
24,923
2024-10-05 16:49:03
169,517
2,507
2008-10-04 01:41:55
2,908
2016-04-23 00:41:06
https://stackoverflow.com/q/169511
https://stackoverflow.com/a/169517
<pre><code>for i in $(seq 1 $END); do echo $i; done</code></pre> <p>edit: I prefer <code>seq</code> over the other methods because I can actually remember it ;)</p>
<pre><code>for i in $(seq 1 $END); do echo $i; done</code></pre> <p>edit: I prefer <code>seq</code> over the other methods because I can actually remember it ;)</p>
367, 387, 390, 2531
bash, for-loop, shell, syntax
<h1>How do I iterate over a range of numbers defined by variables in Bash?</h1> <p>How do I iterate over a range of numbers in Bash when the range is given by a variable?</p> <p>I know I can do this (called &quot;sequence expression&quot; in the Bash <a href="http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion" rel="noreferrer">documentation</a>):</p> <pre><code>for i in {1..5}; do echo $i; done </code></pre> <p>Which gives:</p> <blockquote> <p>1 <br/> 2 <br/> 3 <br/> 4 <br/> 5</p> </blockquote> <p>Yet, how can I replace either of the range endpoints with a variable? This doesn't work:</p> <pre><code>END=5 for i in {1..$END}; do echo $i; done </code></pre> <p>Which prints:</p> <blockquote> <p>{1..5}</p> </blockquote>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
45
bash
# How do I iterate over a range of numbers defined by variables in Bash? How do I iterate over a range of numbers in Bash when the range is given by a variable? I know I can do this (called "sequence expression" in the Bash [documentation](http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion)): ``` for i in {1..5}; do echo $i; done ``` Which gives: > 1 > 2 > 3 > 4 > 5 Yet, how can I replace either of the range endpoints with a variable? This doesn't work: ``` END=5 for i in {1..$END}; do echo $i; done ``` Which prints: > {1..5}
``` for i in $(seq 1 $END); do echo $i; done ``` edit: I prefer `seq` over the other methods because I can actually remember it ;)
1401482
YYYY-MM-DD format date in shell script
1,617
2009-09-09 19:06:56
<p>I tried using <code>$(date)</code> in my bash shell script, however, I want the date in <code>YYYY-MM-DD</code> format.<br> How do I get this?</p>
2,304,731
45,730
2024-08-06 13:04:41
1,401,495
2,406
2009-09-09 19:08:57
11,123
2024-08-06 13:04:41
https://stackoverflow.com/q/1401482
https://stackoverflow.com/a/1401495
<p>In bash (&gt;=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external <code>date</code> (usually GNU date). Note that invoking a subshell has performance problems in Cygwin due to a slow <code>fork()</code> call on Windows.</p> <p>As such:</p> <pre><code># put current date as yyyy-mm-dd in $date # -1 -&gt; explicit current date, bash &gt;=4.3 defaults to current time if not provided # -2 -&gt; start time for shell printf -v date '%(%Y-%m-%d)T\n' -1 # put current date as yyyy-mm-dd HH:MM:SS in $date printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1 # to print directly remove -v flag, as such: printf '%(%Y-%m-%d)T\n' -1 # -&gt; current date printed to terminal </code></pre> <p>In bash (&lt;4.2):</p> <pre><code># put current date as yyyy-mm-dd in $date date=$(date '+%Y-%m-%d') # put current date as yyyy-mm-dd HH:MM:SS in $date date=$(date '+%Y-%m-%d %H:%M:%S') # print current date directly echo $(date '+%Y-%m-%d') </code></pre> <p>Other available date formats can be viewed from the <a href="http://man7.org/linux/man-pages/man1/date.1.html" rel="noreferrer">date man pages</a> (for external non-bash specific command):</p> <pre><code>man date </code></pre>
<p>In bash (&gt;=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external <code>date</code> (usually GNU date). Note that invoking a subshell has performance problems in Cygwin due to a slow <code>fork()</code> call on Windows.</p> <p>As such:</p> <pre><code># put current date as yyyy-mm-dd in $date # -1 -&gt; explicit current date, bash &gt;=4.3 defaul
387, 390, 5002, 10823, 35771
bash, date, date-formatting, shell, strftime
<h1>YYYY-MM-DD format date in shell script</h1> <p>I tried using <code>$(date)</code> in my bash shell script, however, I want the date in <code>YYYY-MM-DD</code> format.<br> How do I get this?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
46
bash
# YYYY-MM-DD format date in shell script I tried using `$(date)` in my bash shell script, however, I want the date in `YYYY-MM-DD` format. How do I get this?
In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external `date` (usually GNU date). Note that invoking a subshell has performance problems in Cygwin due to a slow `fork()` call on Windows. As such: ``` # put current date as yyyy-mm-dd in $date # -1 -> explicit current date, bash >=4.3 defaults to current time if not provided # -2 -> start time for shell printf -v date '%(%Y-%m-%d)T\n' -1 # put current date as yyyy-mm-dd HH:MM:SS in $date printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1 # to print directly remove -v flag, as such: printf '%(%Y-%m-%d)T\n' -1 # -> current date printed to terminal ``` In bash (<4.2): ``` # put current date as yyyy-mm-dd in $date date=$(date '+%Y-%m-%d') # put current date as yyyy-mm-dd HH:MM:SS in $date date=$(date '+%Y-%m-%d %H:%M:%S') # print current date directly echo $(date '+%Y-%m-%d') ``` Other available date formats can be viewed from the [date man pages](http://man7.org/linux/man-pages/man1/date.1.html) (for external non-bash specific command): ``` man date ```
6212219
Passing parameters to a Bash function
1,578
2011-06-02 08:35:17
<p>I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the <em>command line</em>.</p> <p>I would like to pass parameters within my script. I tried:</p> <pre><code>myBackupFunction(&quot;..&quot;, &quot;...&quot;, &quot;xx&quot;) function myBackupFunction($directory, $options, $rootPassword) { ... } </code></pre> <p>But the syntax is not correct. How can I pass a parameter to my function?</p>
2,039,197
445,543
2024-11-20 15:20:36
6,212,408
2,399
2011-06-02 08:57:02
7,412
2020-12-18 16:27:37
https://stackoverflow.com/q/6212219
https://stackoverflow.com/a/6212408
<p>There are two typical ways of declaring a function. I prefer the second approach.</p> <pre><code>function function_name { command... } </code></pre> <p>or</p> <pre><code>function_name () { command... } </code></pre> <p>To call a function with arguments:</p> <pre><code>function_name &quot;$arg1&quot; &quot;$arg2&quot; </code></pre> <p>The function refers to passed arguments by their position (not by name), that is <code>$1</code>, <code>$2</code>, and so forth. <strong><code>$0</code></strong> is the name of the script itself.</p> <p>Example:</p> <pre><code>function_name () { echo &quot;Parameter #1 is $1&quot; } </code></pre> <p>Also, you need to call your function <strong>after</strong> it is declared.</p> <pre><code>#!/usr/bin/env sh foo 1 # this will fail because foo has not been declared yet. foo() { echo &quot;Parameter #1 is $1&quot; } foo 2 # this will work. </code></pre> <p><strong>Output:</strong></p> <pre class="lang-none prettyprint-override"><code>./myScript.sh: line 2: foo: command not found Parameter #1 is 2 </code></pre> <p><a href="http://tldp.org/LDP/abs/html/complexfunct.html" rel="noreferrer">Reference: Advanced Bash-Scripting Guide</a>.</p>
<p>There are two typical ways of declaring a function. I prefer the second approach.</p> <pre><code>function function_name { command... } </code></pre> <p>or</p> <pre><code>function_name () { command... } </code></pre> <p>To call a function with arguments:</p> <pre><code>function_name &quot;$arg1&quot; &quot;$arg2&quot; </code></pre> <p>The function refers to passed arguments by their posi
360, 387, 2313, 5569
arguments, bash, function, parameters
<h1>Passing parameters to a Bash function</h1> <p>I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the <em>command line</em>.</p> <p>I would like to pass parameters within my script. I tried:</p> <pre><code>myBackupFunction(&quot;..&quot;, &quot;...&quot;, &quot;xx&quot;) function myBackupFunction($directory, $options, $rootPassword) { ... } </code></pre> <p>But the syntax is not correct. How can I pass a parameter to my function?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
47
bash
# Passing parameters to a Bash function I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the *command line*. I would like to pass parameters within my script. I tried: ``` myBackupFunction("..", "...", "xx") function myBackupFunction($directory, $options, $rootPassword) { ... } ``` But the syntax is not correct. How can I pass a parameter to my function?
There are two typical ways of declaring a function. I prefer the second approach. ``` function function_name { command... } ``` or ``` function_name () { command... } ``` To call a function with arguments: ``` function_name "$arg1" "$arg2" ``` The function refers to passed arguments by their position (not by name), that is `$1`, `$2`, and so forth. **`$0`** is the name of the script itself. Example: ``` function_name () { echo "Parameter #1 is $1" } ``` Also, you need to call your function **after** it is declared. ``` #!/usr/bin/env sh foo 1 # this will fail because foo has not been declared yet. foo() { echo "Parameter #1 is $1" } foo 2 # this will work. ``` **Output:** ``` ./myScript.sh: line 2: foo: command not found Parameter #1 is 2 ``` [Reference: Advanced Bash-Scripting Guide](http://tldp.org/LDP/abs/html/complexfunct.html).
13210880
Replace one substring for another string in shell script
1,457
2012-11-03 16:01:23
<p>I have &quot;I love Suzi and Marry&quot; and I want to change &quot;Suzi&quot; to &quot;Sara&quot;.</p> <pre><code>firstString=&quot;I love Suzi and Marry&quot; secondString=&quot;Sara&quot; </code></pre> <p>Desired result:</p> <pre><code>firstString=&quot;I love Sara and Marry&quot; </code></pre>
1,824,557
1,796,726
2024-06-17 13:39:36
13,210,909
2,391
2012-11-03 16:05:06
978,917
2024-06-17 13:39:36
https://stackoverflow.com/q/13210880
https://stackoverflow.com/a/13210909
<p>To replace the <em>first</em> occurrence of a pattern with a given string, use <code>${<em>parameter</em>/<em>pattern</em>/<em>string</em>}</code>:</p> <pre><code>#!/bin/bash firstString=&quot;I love Suzi and Marry&quot; secondString=&quot;Sara&quot; echo &quot;${firstString/Suzi/&quot;$secondString&quot;}&quot; # prints 'I love Sara and Marry' </code></pre> <p>To replace <em>all</em> occurrences, use <code>${<em>parameter</em>//<em>pattern</em>/<em>string</em>}</code>:</p> <pre><code>message='The secret code is 12345' echo &quot;${message//[0-9]/X}&quot; # prints 'The secret code is XXXXX' </code></pre> <p>(This is documented in <a href="https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion" rel="noreferrer">the <em>Bash Reference Manual</em>, §3.5.3 &quot;Shell Parameter Expansion&quot;</a>.)</p> <p>Note that this feature is not specified by POSIX — it's a Bash extension — so not all Unix shells implement it. For the relevant POSIX documentation, see <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02" rel="noreferrer"><em>The Open Group Technical Standard Base Specifications, Issue 7</em>, the <em>Shell &amp; Utilities</em> volume, §2.6.2 &quot;Parameter Expansion&quot;</a>.</p>
<p>To replace the <em>first</em> occurrence of a pattern with a given string, use <code>${<em>parameter</em>/<em>pattern</em>/<em>string</em>}</code>:</p> <pre><code>#!/bin/bash firstString=&quot;I love Suzi and Marry&quot; secondString=&quot;Sara&quot; echo &quot;${firstString/Suzi/&quot;$secondString&quot;}&quot; # prints 'I love Sara and Marry' </code></pre> <p>To replace <em>all</em> occurrenc
387, 390
bash, shell
<h1>Replace one substring for another string in shell script</h1> <p>I have &quot;I love Suzi and Marry&quot; and I want to change &quot;Suzi&quot; to &quot;Sara&quot;.</p> <pre><code>firstString=&quot;I love Suzi and Marry&quot; secondString=&quot;Sara&quot; </code></pre> <p>Desired result:</p> <pre><code>firstString=&quot;I love Sara and Marry&quot; </code></pre>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
48
bash
# Replace one substring for another string in shell script I have "I love Suzi and Marry" and I want to change "Suzi" to "Sara". ``` firstString="I love Suzi and Marry" secondString="Sara" ``` Desired result: ``` firstString="I love Sara and Marry" ```
To replace the *first* occurrence of a pattern with a given string, use `${parameter/pattern/string}`: ``` #!/bin/bash firstString="I love Suzi and Marry" secondString="Sara" echo "${firstString/Suzi/"$secondString"}" # prints 'I love Sara and Marry' ``` To replace *all* occurrences, use `${parameter//pattern/string}`: ``` message='The secret code is 12345' echo "${message//[0-9]/X}" # prints 'The secret code is XXXXX' ``` (This is documented in [the *Bash Reference Manual*, §3.5.3 "Shell Parameter Expansion"](https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion).) Note that this feature is not specified by POSIX — it's a Bash extension — so not all Unix shells implement it. For the relevant POSIX documentation, see [*The Open Group Technical Standard Base Specifications, Issue 7*, the *Shell & Utilities* volume, §2.6.2 "Parameter Expansion"](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02).
418896
How to redirect output to a file and stdout
1,677
2009-01-07 01:45:42
<p>In bash, calling <code>foo</code> would display any output from that command on the stdout.</p> <p>Calling <code>foo &gt; output</code> would redirect any output from that command to the file specified (in this case 'output').</p> <p>Is there a way to redirect output to a file <em>and</em> have it display on stdout?</p>
1,246,622
1,666
2024-03-19 09:17:37
418,899
2,378
2009-01-07 01:48:08
20,267
2017-10-23 17:10:56
https://stackoverflow.com/q/418896
https://stackoverflow.com/a/418899
<p>The command you want is named <strong><a href="http://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html" rel="noreferrer"><code>tee</code></a></strong>:</p> <pre><code>foo | tee output.file </code></pre> <p>For example, if you only care about stdout:</p> <pre><code>ls -a | tee output.file </code></pre> <p>If you want to include stderr, do:</p> <pre><code>program [arguments...] 2&gt;&amp;1 | tee outfile </code></pre> <p><code>2&gt;&amp;1</code> redirects channel 2 (stderr/standard error) into channel 1 (stdout/standard output), such that both is written as stdout. It is also directed to the given output file as of the <code>tee</code> command.</p> <p>Furthermore, if you want to <em>append</em> to the log file, use <code>tee -a</code> as:</p> <pre><code>program [arguments...] 2&gt;&amp;1 | tee -a outfile </code></pre>
<p>The command you want is named <strong><a href="http://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html" rel="noreferrer"><code>tee</code></a></strong>:</p> <pre><code>foo | tee output.file </code></pre> <p>For example, if you only care about stdout:</p> <pre><code>ls -a | tee output.file </code></pre> <p>If you want to include stderr, do:</p> <pre><code>program [argument
58, 345, 387, 724, 4867
bash, file-io, io, linux, stdout
<h1>How to redirect output to a file and stdout</h1> <p>In bash, calling <code>foo</code> would display any output from that command on the stdout.</p> <p>Calling <code>foo &gt; output</code> would redirect any output from that command to the file specified (in this case 'output').</p> <p>Is there a way to redirect output to a file <em>and</em> have it display on stdout?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
49
bash
# How to redirect output to a file and stdout In bash, calling `foo` would display any output from that command on the stdout. Calling `foo > output` would redirect any output from that command to the file specified (in this case 'output'). Is there a way to redirect output to a file *and* have it display on stdout?
The command you want is named **[`tee`](http://www.gnu.org/software/coreutils/manual/html_node/tee-invocation.html)**: ``` foo | tee output.file ``` For example, if you only care about stdout: ``` ls -a | tee output.file ``` If you want to include stderr, do: ``` program [arguments...] 2>&1 | tee outfile ``` `2>&1` redirects channel 2 (stderr/standard error) into channel 1 (stdout/standard output), such that both is written as stdout. It is also directed to the given output file as of the `tee` command. Furthermore, if you want to *append* to the log file, use `tee -a` as: ``` program [arguments...] 2>&1 | tee -a outfile ```
4608187
How to reload .bash_profile from the command line
1,234
2011-01-05 19:09:07
<p>How can I reload file <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)#Legacy-compatible_Bash_startup_example" rel="noreferrer">.bash_profile</a> from the <em>command line</em>?</p> <p>I can get the shell to recognize changes to <em>.bash_profile</em> by exiting and logging back in, but I would like to be able to do it on demand.</p>
1,217,536
97,101
2024-10-08 02:19:42
4,608,197
2,292
2011-01-05 19:10:03
207,248
2024-10-08 02:19:42
https://stackoverflow.com/q/4608187
https://stackoverflow.com/a/4608197
<p>Simply type <code>source ~/.bash_profile</code></p> <p>Alternatively, if you like saving keystrokes, you can type <code>. ~/.bash_profile</code></p>
<p>Simply type <code>source ~/.bash_profile</code></p> <p>Alternatively, if you like saving keystrokes, you can type <code>. ~/.bash_profile</code></p>
387, 390, 1231
bash, command-line, shell
<h1>How to reload .bash_profile from the command line</h1> <p>How can I reload file <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)#Legacy-compatible_Bash_startup_example" rel="noreferrer">.bash_profile</a> from the <em>command line</em>?</p> <p>I can get the shell to recognize changes to <em>.bash_profile</em> by exiting and logging back in, but I would like to be able to do it on demand.</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
50
bash
# How to reload .bash_profile from the command line How can I reload file [.bash_profile](https://en.wikipedia.org/wiki/Bash_(Unix_shell)#Legacy-compatible_Bash_startup_example) from the *command line*? I can get the shell to recognize changes to *.bash_profile* by exiting and logging back in, but I would like to be able to do it on demand.
Simply type `source ~/.bash_profile` Alternatively, if you like saving keystrokes, you can type `. ~/.bash_profile`
343646
Ignoring directories in Git repositories on Windows
1,592
2008-12-05 12:17:28
<p>How can I ignore directories or folders in Git using msysgit on Windows?</p>
2,050,509
43,603
2025-05-29 14:10:31
343,734
2,241
2008-12-05 12:54:10
43,613
2019-11-14 13:48:32
https://stackoverflow.com/q/343646
https://stackoverflow.com/a/343734
<p>Create a file named <code>.gitignore</code> in your project's directory. Ignore directories by entering the directory name into the file (with a slash appended):</p> <pre><code>dir_to_ignore/ </code></pre> <p>More information is <a href="http://git-scm.com/docs/gitignore" rel="noreferrer">here</a>.</p>
<p>Create a file named <code>.gitignore</code> in your project's directory. Ignore directories by entering the directory name into the file (with a slash appended):</p> <pre><code>dir_to_ignore/ </code></pre> <p>More information is <a href="http://git-scm.com/docs/gitignore" rel="noreferrer">here</a>.</p>
64, 119, 21628, 25056, 61874
git, git-bash, gitignore, msysgit, windows
<h1>Ignoring directories in Git repositories on Windows</h1> <p>How can I ignore directories or folders in Git using msysgit on Windows?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
51
bash
# Ignoring directories in Git repositories on Windows How can I ignore directories or folders in Git using msysgit on Windows?
Create a file named `.gitignore` in your project's directory. Ignore directories by entering the directory name into the file (with a slash appended): ``` dir_to_ignore/ ``` More information is [here](http://git-scm.com/docs/gitignore).
2990414
echo that outputs to stderr
1,686
2010-06-07 14:36:16
<p>Is there a standard Bash command that acts like <code>echo</code> but outputs to stderr rather than stdout?</p> <p>I know I can do <code>echo foo 1&gt;&amp;2</code> but it's kinda ugly and, I suspect, error-prone (e.g. more likely to get edited wrong when things change).</p>
1,048,664
1,343
2023-10-10 06:11:19
23,550,347
2,201
2014-05-08 18:59:47
675,584
2023-05-09 22:29:35
https://stackoverflow.com/q/2990414
https://stackoverflow.com/a/23550347
<p>You could do this, which facilitates reading:</p> <pre><code>&gt;&amp;2 echo &quot;error&quot; </code></pre> <p><code>&gt;&amp;2</code> copies file descriptor #2 to file descriptor #1. Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was <strong>originally</strong> referring to. For more information see the <a href="https://web.archive.org/web/20230315225157/https://wiki.bash-hackers.org/howto/redirection_tutorial" rel="noreferrer">Bash Hackers Illustrated Redirection Tutorial</a>.</p>
<p>You could do this, which facilitates reading:</p> <pre><code>&gt;&amp;2 echo &quot;error&quot; </code></pre> <p><code>&gt;&amp;2</code> copies file descriptor #2 to file descriptor #1. Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was <strong>originally</strong> referring to. For more information see the <a href="ht
387
bash
<h1>echo that outputs to stderr</h1> <p>Is there a standard Bash command that acts like <code>echo</code> but outputs to stderr rather than stdout?</p> <p>I know I can do <code>echo foo 1&gt;&amp;2</code> but it's kinda ugly and, I suspect, error-prone (e.g. more likely to get edited wrong when things change).</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
52
bash
# echo that outputs to stderr Is there a standard Bash command that acts like `echo` but outputs to stderr rather than stdout? I know I can do `echo foo 1>&2` but it's kinda ugly and, I suspect, error-prone (e.g. more likely to get edited wrong when things change).
You could do this, which facilitates reading: ``` >&2 echo "error" ``` `>&2` copies file descriptor #2 to file descriptor #1. Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was **originally** referring to. For more information see the [Bash Hackers Illustrated Redirection Tutorial](https://web.archive.org/web/20230315225157/https://wiki.bash-hackers.org/howto/redirection_tutorial).
226703
How do I prompt for Yes/No/Cancel input in a Linux shell script?
1,921
2008-10-22 17:03:22
<p>I want to pause input in a shell script, and prompt the user for choices.<br> The standard <code>Yes</code>, <code>No</code>, or <code>Cancel</code> type question.<br> How do I accomplish this in a typical bash prompt?</p>
1,415,315
9,084
2026-01-06 20:54:44
226,724
2,092
2008-10-22 17:08:50
9,084
2025-03-18 14:21:37
https://stackoverflow.com/q/226703
https://stackoverflow.com/a/226724
<p>A widely available method to get user input at a shell prompt is the <a href="https://www.gnu.org/software/bash/manual/bashref.html#index-read" rel="noreferrer"><code>read</code></a> command. Here is a demonstration:</p> <pre><code>while true; do read -p &quot;Do you wish to install this program? &quot; yn case $yn in [Yy]* ) make install; break;; [Nn]* ) exit;; * ) echo &quot;Please answer yes or no.&quot;;; esac done </code></pre> <hr /> <p>Another method, <a href="https://stackoverflow.com/a/226946/9084">pointed out</a> by <a href="https://stackoverflow.com/users/28604/steven-huwig">Steven Huwig</a>, is Bash's <a href="https://www.gnu.org/software/bash/manual/bashref.html#index-select" rel="noreferrer"><code>select</code></a> command. Here is the same example using <code>select</code>:</p> <pre><code>echo &quot;Do you wish to install this program?&quot; select yn in &quot;Yes&quot; &quot;No&quot;; do case $yn in Yes ) make install; break;; No ) exit;; esac done </code></pre> <p>With <code>select</code> you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a <code>while true</code> loop to retry if they give invalid input. If you want to allow more flexible input (accepting the words of the options, rather than <a href="https://www.gnu.org/software/bash/manual/bashref.html#index-select" rel="noreferrer">just their number</a>), you can alter it like this:</p> <pre><code>echo &quot;Do you wish to install this program?&quot; select strictreply in &quot;Yes&quot; &quot;No&quot;; do relaxedreply=${strictreply:-$REPLY} case $relaxedreply in Yes | yes | y ) make install; break;; No | no | n ) exit;; esac done </code></pre> <hr /> <p>Also, <a href="https://stackoverflow.com/users/7939871/l%c3%a9a-gris">Léa Gris</a> demonstrated a way to make the request language agnostic in <a href="https://stackoverflow.com/a/57739142/9084">her answer</a>. Adapting my first example to better serve multiple languages might look like this:</p> <pre><code>set -- $(locale LC_MESSAGES) yesexpr=&quot;$1&quot;; noexpr=&quot;$2&quot;; yesword=&quot;$3&quot;; noword=&quot;$4&quot; while true; do read -p &quot;Install (${yesword} / ${noword})? &quot; yn if [[ &quot;$yn&quot; =~ $yesexpr ]]; then make install; exit; fi if [[ &quot;$yn&quot; =~ $noexpr ]]; then exit; fi echo &quot;Answer ${yesword} / ${noword}.&quot; done </code></pre> <p>Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.</p> <hr /> <p>Finally, please check out the <a href="https://stackoverflow.com/a/27875395/9084">excellent answer</a> by <a href="https://stackoverflow.com/users/1765658/f-hauri">F. Hauri</a>.</p>
<p>A widely available method to get user input at a shell prompt is the <a href="https://www.gnu.org/software/bash/manual/bashref.html#index-read" rel="noreferrer"><code>read</code></a> command. Here is a demonstration:</p> <pre><code>while true; do read -p &quot;Do you wish to install this program? &quot; yn case $yn in [Yy]* ) make install; break;; [Nn]* ) exit;;
58, 387, 390, 531
bash, linux, scripting, shell
<h1>How do I prompt for Yes/No/Cancel input in a Linux shell script?</h1> <p>I want to pause input in a shell script, and prompt the user for choices.<br> The standard <code>Yes</code>, <code>No</code>, or <code>Cancel</code> type question.<br> How do I accomplish this in a typical bash prompt?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
53
bash
# How do I prompt for Yes/No/Cancel input in a Linux shell script? I want to pause input in a shell script, and prompt the user for choices. The standard `Yes`, `No`, or `Cancel` type question. How do I accomplish this in a typical bash prompt?
A widely available method to get user input at a shell prompt is the [`read`](https://www.gnu.org/software/bash/manual/bashref.html#index-read) command. Here is a demonstration: ``` while true; do read -p "Do you wish to install this program? " yn case $yn in [Yy]* ) make install; break;; [Nn]* ) exit;; * ) echo "Please answer yes or no.";; esac done ``` --- Another method, [pointed out](https://stackoverflow.com/a/226946/9084) by [Steven Huwig](https://stackoverflow.com/users/28604/steven-huwig), is Bash's [`select`](https://www.gnu.org/software/bash/manual/bashref.html#index-select) command. Here is the same example using `select`: ``` echo "Do you wish to install this program?" select yn in "Yes" "No"; do case $yn in Yes ) make install; break;; No ) exit;; esac done ``` With `select` you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a `while true` loop to retry if they give invalid input. If you want to allow more flexible input (accepting the words of the options, rather than [just their number](https://www.gnu.org/software/bash/manual/bashref.html#index-select)), you can alter it like this: ``` echo "Do you wish to install this program?" select strictreply in "Yes" "No"; do relaxedreply=${strictreply:-$REPLY} case $relaxedreply in Yes | yes | y ) make install; break;; No | no | n ) exit;; esac done ``` --- Also, [Léa Gris](https://stackoverflow.com/users/7939871/l%c3%a9a-gris) demonstrated a way to make the request language agnostic in [her answer](https://stackoverflow.com/a/57739142/9084). Adapting my first example to better serve multiple languages might look like this: ``` set -- $(locale LC_MESSAGES) yesexpr="$1"; noexpr="$2"; yesword="$3"; noword="$4" while true; do read -p "Install (${yesword} / ${noword})? " yn if [[ "$yn" =~ $yesexpr ]]; then make install; exit; fi if [[ "$yn" =~ $noexpr ]]; then exit; fi echo "Answer ${yesword} / ${noword}." done ``` Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases. --- Finally, please check out the [excellent answer](https://stackoverflow.com/a/27875395/9084) by [F. Hauri](https://stackoverflow.com/users/1765658/f-hauri).
4824590
Propagate all arguments in a Bash shell script
1,291
2011-01-28 03:34:04
<p>I am writing a very simple script that calls another script, and I need to propagate the parameters from my current script to the script I am executing.</p> <p>For instance, my script name is <code>foo.sh</code> and calls <code>bar.sh</code>.</p> <p>foo.sh:</p> <pre><code>bar $1 $2 $3 $4 </code></pre> <p>How can I do this without explicitly specifying each parameter?</p>
737,326
121,112
2026-01-14 22:40:28
4,824,637
2,024
2011-01-28 03:42:43
401,390
2026-01-14 22:40:28
https://stackoverflow.com/q/4824590
https://stackoverflow.com/a/4824637
<p>Use <code>&quot;$@&quot;</code> instead of plain <code>$@</code> if you actually wish your parameters to be passed exactly as is.</p> <p>Observe:</p> <pre class="lang-bash prettyprint-override"><code>$ cat no_quotes.sh #!/bin/bash ./echo_args.sh $@ $ cat quotes.sh #!/bin/bash ./echo_args.sh &quot;$@&quot; $ cat echo_args.sh #!/bin/bash echo Received: $1 echo Received: $2 echo Received: $3 echo Received: $4 $ ./no_quotes.sh first second Received: first Received: second Received: Received: $ ./no_quotes.sh &quot;one quoted arg&quot; Received: one Received: quoted Received: arg Received: $ ./quotes.sh first second Received: first Received: second Received: Received: $ ./quotes.sh &quot;one quoted arg&quot; Received: one quoted arg Received: Received: Received: </code></pre>
<p>Use <code>&quot;$@&quot;</code> instead of plain <code>$@</code> if you actually wish your parameters to be passed exactly as is.</p> <p>Observe:</p> <pre class="lang-bash prettyprint-override"><code>$ cat no_quotes.sh #!/bin/bash ./echo_args.sh $@ $ cat quotes.sh #!/bin/bash ./echo_args.sh &quot;$@&quot; $ cat echo_args.sh #!/bin/bash echo Received: $1 echo Received: $2 echo Received: $3 ech
387, 31134
bash, command-line-arguments
<h1>Propagate all arguments in a Bash shell script</h1> <p>I am writing a very simple script that calls another script, and I need to propagate the parameters from my current script to the script I am executing.</p> <p>For instance, my script name is <code>foo.sh</code> and calls <code>bar.sh</code>.</p> <p>foo.sh:</p> <pre><code>bar $1 $2 $3 $4 </code></pre> <p>How can I do this without explicitly specifying each parameter?</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
54
bash
# Propagate all arguments in a Bash shell script I am writing a very simple script that calls another script, and I need to propagate the parameters from my current script to the script I am executing. For instance, my script name is `foo.sh` and calls `bar.sh`. foo.sh: ``` bar $1 $2 $3 $4 ``` How can I do this without explicitly specifying each parameter?
Use `"$@"` instead of plain `$@` if you actually wish your parameters to be passed exactly as is. Observe: ``` $ cat no_quotes.sh #!/bin/bash ./echo_args.sh $@ $ cat quotes.sh #!/bin/bash ./echo_args.sh "$@" $ cat echo_args.sh #!/bin/bash echo Received: $1 echo Received: $2 echo Received: $3 echo Received: $4 $ ./no_quotes.sh first second Received: first Received: second Received: Received: $ ./no_quotes.sh "one quoted arg" Received: one Received: quoted Received: arg Received: $ ./quotes.sh first second Received: first Received: second Received: Received: $ ./quotes.sh "one quoted arg" Received: one quoted arg Received: Received: Received: ```
255898
How to iterate over arguments in a Bash script
1,205
2008-11-01 18:14:21
<p>I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of <code>$1</code> easily:</p> <pre><code>foo $1 args -o $1.ext </code></pre> <p>I want to be able to pass multiple input names to the script. What's the right way to do it? </p> <p>And, of course, I want to handle filenames with spaces in them.</p>
968,520
12,874
2023-07-31 17:02:04
255,913
2,010
2008-11-01 18:25:27
25,222
2023-07-31 17:02:04
https://stackoverflow.com/q/255898
https://stackoverflow.com/a/255913
<p>Use <code>&quot;$@&quot;</code> to represent all the arguments:</p> <pre><code>for var in &quot;$@&quot; do echo &quot;$var&quot; done </code></pre> <p>This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that, when quoted, the arguments are broken up properly if there are spaces in them:</p> <pre><code>sh test.sh 1 2 '3 4' 1 2 3 4 </code></pre>
<p>Use <code>&quot;$@&quot;</code> to represent all the arguments:</p> <pre><code>for var in &quot;$@&quot; do echo &quot;$var&quot; done </code></pre> <p>This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that, when quoted, the arguments are broken up properly if there are spaces in them:</p> <pre><code>sh test.sh 1 2 '3 4' 1 2 3 4 </code></pr
387, 1231
bash, command-line
<h1>How to iterate over arguments in a Bash script</h1> <p>I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of <code>$1</code> easily:</p> <pre><code>foo $1 args -o $1.ext </code></pre> <p>I want to be able to pass multiple input names to the script. What's the right way to do it? </p> <p>And, of course, I want to handle filenames with spaces in them.</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
55
bash
# How to iterate over arguments in a Bash script I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of `$1` easily: ``` foo $1 args -o $1.ext ``` I want to be able to pass multiple input names to the script. What's the right way to do it? And, of course, I want to handle filenames with spaces in them.
Use `"$@"` to represent all the arguments: ``` for var in "$@" do echo "$var" done ``` This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that, when quoted, the arguments are broken up properly if there are spaces in them: ``` sh test.sh 1 2 '3 4' 1 2 3 4 ```
1250079
How to escape single quotes within single quoted strings
1,494
2009-08-08 22:50:10
<p>Let's say, you have a Bash <code>alias</code> like:</p> <pre><code>alias rxvt='urxvt' </code></pre> <p>which works fine.</p> <p>However:</p> <pre class="lang-none prettyprint-override"><code>alias rxvt='urxvt -fg '#111111' -bg '#111111'' </code></pre> <p>won't work, and neither will:</p> <pre><code>alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\'' </code></pre> <p>So how do you end up matching up opening and closing quotes inside a string once you have escaped quotes?</p> <pre><code>alias rxvt='urxvt -fg'\''#111111'\'' -bg '\''#111111'\'' </code></pre> <p>seems ungainly although it would represent the same string if you're allowed to concatenate them like that.</p>
813,241
152,404
2025-05-29 14:58:14
1,250,279
2,002
2009-08-09 00:52:37
42,610
2024-03-11 23:33:18
https://stackoverflow.com/q/1250079
https://stackoverflow.com/a/1250279
<p>If you really want to use single quotes in the outermost layer, remember that you can glue both kinds of quotation. Example:</p> <pre><code> alias rxvt='urxvt -fg '&quot;'&quot;'#111111'&quot;'&quot;' -bg '&quot;'&quot;'#111111'&quot;'&quot; # ^^^^^ ^^^^^ ^^^^^ ^^^^ # 12345 12345 12345 1234 </code></pre> <p>Explanation of how <code>'&quot;'&quot;'</code> is interpreted as just <code>'</code>:</p> <ol> <li><code>'</code> End first quotation which uses single quotes.</li> <li><code>&quot;</code> Start second quotation, using double-quotes.</li> <li><code>'</code> Quoted character.</li> <li><code>&quot;</code> End second quotation, using double-quotes.</li> <li><code>'</code> Start third quotation, using single quotes.</li> </ol> <p>If you do not place any whitespaces between (1) and (2), or between (4) and (5), the shell will interpret that string as a one long word:</p> <pre><code>$ echo 'abc''123' abc123 $ echo 'abc'\''123' abc'123 $ echo 'abc'&quot;'&quot;'123' abc'123 </code></pre> <p>It will also keep the internal representation with 'to be joined' strings, and will also prefer the shorter escape syntax when possible:</p> <pre><code>$ alias test='echo '&quot;'&quot;'hi'&quot;'&quot; $ alias test alias test='echo '\''hi'\''' $ test hi </code></pre>
<p>If you really want to use single quotes in the outermost layer, remember that you can glue both kinds of quotation. Example:</p> <pre><code> alias rxvt='urxvt -fg '&quot;'&quot;'#111111'&quot;'&quot;' -bg '&quot;'&quot;'#111111'&quot;'&quot; # ^^^^^ ^^^^^ ^^^^^ ^^^^ # 12345 12345 12345 1234 </code></pre> <p>Explanation of
367, 387, 10804
bash, quoting, syntax
<h1>How to escape single quotes within single quoted strings</h1> <p>Let's say, you have a Bash <code>alias</code> like:</p> <pre><code>alias rxvt='urxvt' </code></pre> <p>which works fine.</p> <p>However:</p> <pre class="lang-none prettyprint-override"><code>alias rxvt='urxvt -fg '#111111' -bg '#111111'' </code></pre> <p>won't work, and neither will:</p> <pre><code>alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\'' </code></pre> <p>So how do you end up matching up opening and closing quotes inside a string once you have escaped quotes?</p> <pre><code>alias rxvt='urxvt -fg'\''#111111'\'' -bg '\''#111111'\'' </code></pre> <p>seems ungainly although it would represent the same string if you're allowed to concatenate them like that.</p>
q.PostTypeId = 1; a.PostTypeId = 2; EXISTS tag '%bash%' OR '%shell%'; a.Body contains code block; q.Score > 5; a.Score > 10
56
bash
# How to escape single quotes within single quoted strings Let's say, you have a Bash `alias` like: ``` alias rxvt='urxvt' ``` which works fine. However: ``` alias rxvt='urxvt -fg '#111111' -bg '#111111'' ``` won't work, and neither will: ``` alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\'' ``` So how do you end up matching up opening and closing quotes inside a string once you have escaped quotes? ``` alias rxvt='urxvt -fg'\''#111111'\'' -bg '\''#111111'\'' ``` seems ungainly although it would represent the same string if you're allowed to concatenate them like that.
If you really want to use single quotes in the outermost layer, remember that you can glue both kinds of quotation. Example: ``` alias rxvt='urxvt -fg '"'"'#111111'"'"' -bg '"'"'#111111'"'" # ^^^^^ ^^^^^ ^^^^^ ^^^^ # 12345 12345 12345 1234 ``` Explanation of how `'"'"'` is interpreted as just `'`: 1. `'` End first quotation which uses single quotes. 2. `"` Start second quotation, using double-quotes. 3. `'` Quoted character. 4. `"` End second quotation, using double-quotes. 5. `'` Start third quotation, using single quotes. If you do not place any whitespaces between (1) and (2), or between (4) and (5), the shell will interpret that string as a one long word: ``` $ echo 'abc''123' abc123 $ echo 'abc'\''123' abc'123 $ echo 'abc'"'"'123' abc'123 ``` It will also keep the internal representation with 'to be joined' strings, and will also prefer the shorter escape syntax when possible: ``` $ alias test='echo '"'"'hi'"'" $ alias test alias test='echo '\''hi'\''' $ test hi ```
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
13