2

I'm trying to write a simple shell script, but am struggling to figure out why I can't keep spaces in a string variable that I use to produce file names in a shell script.

#!/bin/bash

let minus3=10#$(date +%Y)-3
let minus2=10#$(date +%Y)-2
string="$minus3 - $minus2"
dir="'$minus3\ -\ $minus2'"
printf "\nIt is $(date +%Y).\nWe will be moving files from $string today.\n\n"

The commands that produce multiple incorrectly names directories because of the space:

mkdir $dir
mkdir $string
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 1
    you need to quote the variable... `mkdir "$string"`... see https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters – Sundeep Jul 20 '17 at 16:05
  • @Sundeep Thanks! That worked. – manicmarvin Jul 20 '17 at 16:07
  • 2
    BTW, http://shellcheck.net/ will catch this (inadequate quoting) class of bugs. – Charles Duffy Jul 20 '17 at 16:08
  • 2
    (It's also covered in [Bash Pitfalls](http://mywiki.wooledge.org/BashPitfalls), which is worth reading in its own right). – Charles Duffy Jul 20 '17 at 16:10
  • (`mkdir "$minuse3 - $minus2"` thus works perfectly; one certainly doesn't _need_ the backslashes for something to be correct, as the self-answer currently edited into the question implies) – Charles Duffy Jul 23 '20 at 14:47
  • ...btw, self-answers do not belong in questions, and that's true even when the question is closed. See [What should I do when the answer of a (closed) question is added to the question?](https://meta.stackoverflow.com/questions/377643) on [meta]. – Charles Duffy Jul 23 '20 at 14:48

0 Answers0