← Back to Bash Course | Chapter 3: Control Flow | Lesson 3 of 14

printf कमांड

printf names और numbers के लिए blanks वाला एक form भरने जैसा है, ताकि आपका output ठीक उसी shape में आए जो आपने plan की थी। echo के विपरीत, यह आखिर में आपके लिए Enter नहीं दबाएगा।

In this page:

  1. printf
Syntax
bash
printf "format string\n" argument1 argument2
# %s string, %d integer, %.2f decimal

printf

printf %s (string), %d (integer), और %.2f (decimal) जैसे format specifiers उपयोग करके output format करता है, C के printf जैसा। echo के विपरीत, यह अपने आप एक trailing newline नहीं जोड़ता — आपको खुद \n शामिल करना होगा।

यह echo से output formatting पर कहीं ज़्यादा precise control देता है।

Note: जब भी आपको aligned columns या fixed decimal places चाहिए तो echo के बजाय printf उपयोग करें।

उदाहरण: printf

bash
#!/bin/bash
printf "Name: %s, Age: %d\n" "Alice" 30
printf "Pi is approximately %.2f\n" 3.14159
printf "%-10s|%5s\n" "left" "right"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Format string में \n भूल जाना, क्योंकि printf खुद से एक newline नहीं जोड़ता।
  2. Arguments की गलत संख्या pass करना, इसलिए format reuse होता है या fields empty रहते हैं।
  3. User input को format string के रूप में उपयोग करना, जैसे printf "$input", जो % पर break हो सकता है; printf '%s\n' "$input" उपयोग करें।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.